Print value in column if criteria has been met in R

Advertisements

I would like to create a column that would create a new column New that would print out the letter associated with that column (second table) if the condition has been met.

The example output looks like the New column below:

Reproducible example:

df <- data.frame(c(1,0,1), c(0,0,1), c(0,1,1), c(1,1,0), c(1,0,0))
names(df) <- paste0("C",1:5)

reftab <- data.frame(col1 = paste0("C",1:5), 
                     col2 = LETTERS[1:5])

>Solution :

I am sure there is a more elegant way, but if you first use apply across rows to find the appropriate letters, then lapply to iterate through those results and paste them together, it should work.

Using these data:

df <- data.frame(c(1,0,1), c(0,0,1), c(0,1,1), c(1,1,0), c(1,0,0))
names(df) <- paste0("C",1:5)

reftab <- data.frame(col1 = paste0("C",1:5), 
                     col2 = LETTERS[1:5])

You can create the new column:

df$New <- lapply(apply(df, 1, \(x) reftab$col2[x == 1]),
                 paste, collapse = "")

Output:

#   C1 C2 C3 C4 C5 New
# 1  1  0  0  1  1 ADE
# 2  0  0  1  1  0  CD
# 3  1  1  1  0  0 ABC

Leave a ReplyCancel reply