Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print value in column if criteria has been met in R

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading