0

I have a sample dataset which is as follows:

 df <- structure(list(Category1 = c("Alpha: 0", "Alpha: 0", "Alpha: 0", 
                                    "Alpha: 3", "Alpha: 0"), 
                      Category2 = c("Beta: 1", "Beta: 0",  "Beta:0", 
                                    "Beta: 1", "Beta: 1"), 
                      Category3 = c("Charlie: 2",  "Charlie: 0",
                                    "Charlie: 0", "Charlie: 2", "Charlie: 2"), 
                      Output = c(NA,  NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, -5L ))

I am trying to add binary values of 1 or 0 in the Output column based on the values in Category1, Category2, Category3 columns. If the value in each of these columns is as follows: "Alpha: 0", "Beta: 0" and "Charlie: 0" then I would like to have "1" added in the same row under the Output column. For any other combinations, I would like to have "0" added in the Output column. Any suggestions on how this can be accomplished in a simplistic manner?

Thanks!

3 Answers 3

2

We can extract the values from each element and use rowSums to check for your condition, i.e.

as.integer(rowSums(sapply(df[-4], function(i)as.numeric(gsub('\\D+', '', i)))) == 0)
#[1] 0 1 1 0 0
Sign up to request clarification or add additional context in comments.

Comments

0

the basic R-way to do this is using ifelse:

df$Output = ifelse(df$Category1 == "Alpha: 0" & df$Category2 == "Beta: 0" & df$Category3 == "Charlie: 0", 1, 0)

df
  Category1 Category2  Category3 Output
1  Alpha: 0   Beta: 1 Charlie: 2      0
2  Alpha: 0   Beta: 0 Charlie: 0      1
3  Alpha: 0   Beta: 0 Charlie: 0      1
4  Alpha: 3   Beta: 1 Charlie: 2      0
5  Alpha: 0   Beta: 1 Charlie: 2      0

1 Comment

Why are you using dplyr's if_else instead of base R ifelse?
0

You can use grepl to test if it contains 0 and all if this is the case for all columns. Put a + infront and you get 0 and 1. Assuming Alpha:, Beta:, Charlie: are there.

+(apply(df[1:3], 1, function(x) all(grepl("0", x))))
#[1] 0 1 1 0 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.