Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

As you can see, I am having a test variable and on that, I am having a table:

test <- data.table(name  = c("mike", "kate", "jeff"), ownership = c("1", "3", "4"), worth = c("1", "2", "3"), tax = c("4", "1", "4"))

I am trying to test if any rows (people) contain a row that contains "1".

I have tried the following but I want my syntax to be a bit more concise.

test <- test[ownership == "1" | worth == "1" | tax == "1", status := "yes"]

1 Answer

0 votes
by (107k points)

For getting the desired output in R programming, you can simply use rowSums() function :

cols <- c('ownership', 'worth', 'tax')

setDT(test)[rowSums(test[, ..cols] == 1) > 0, yes := 'yes']

test

#   name ownership worth tax  yes

#1: mike         1     1   4  yes

#2: kate         3     2   1  yes

#3: jeff         4     3   4 <NA>

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...