Adam
Adam

Reputation: 89

Adding binary values to a column based on pre-defined column values

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!

Upvotes: 0

Views: 99

Answers (3)

Cettt
Cettt

Reputation: 11981

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

Upvotes: 0

GKi
GKi

Reputation: 39657

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

Upvotes: 0

Sotos
Sotos

Reputation: 51582

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

Upvotes: 2

Related Questions