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

Get vector of column names depending on logicals of same dataframe

I have a named dataframe containig logicals with missings and I want to get a vector with the column names where values are TRUE (going down the rows and, if multiple TRUEs in one row, going from left to right). Here an example:

df <- data.frame(a= c(FALSE, NA, TRUE, TRUE),
                 b= c(TRUE, FALSE, FALSE, NA),
                 c= c(TRUE, TRUE, NA, NA))
df
#       a     b    c
# 1 FALSE  TRUE TRUE
# 2    NA FALSE TRUE
# 3  TRUE FALSE   NA
# 4  TRUE    NA   NA

expected <- c("b", "c", "c", "a", "a")

Going from first to last row we see TRUE in the first row. Here are multiple TRUEs, thus we go from left to right and get "b" and "c". In second tow we get "c", and so on.

How to do this (in an elegant way)?

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

>Solution :

You can do in base R:

pos <- which(t(df) == TRUE, arr.ind = TRUE)
names(df)[pos[, "row"]]
[1] "b" "c" "c" "a" "a"
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