Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R select column based on row value

Tags:

r

I have found multiple answers where one can select a row based on a value of a column, but I need the reverse. Consider this example:

library(dplyr)
df <- readr::read_table2("Location       Site     Species    Date     Time
TRUE         TRUE        TRUE       TRUE    TRUE
TRUE         TRUE        TRUE       TRUE    TRUE
TRUE         TRUE        FALSE       TRUE    FALSE
TRUE         TRUE        TRUE     TRUE    TRUE
TRUE       TRUE        TRUE     TRUE    TRUE
TRUE       TRUE        TRUE     TRUE    TRUE")

How can I get the columns or column names which have the values FALSE, considering I know it is in the third row.

I tried something like this: df[3,df[3,]==FALSE], but this gives me an error.

like image 804
MGP Avatar asked Oct 14 '25 14:10

MGP


2 Answers

Maybe something along the lines like this:

df <- readr::read_table2("Location       Site     Species    Date     Time
                          TRUE         TRUE        TRUE       TRUE    TRUE
                          TRUE         TRUE        TRUE       TRUE    TRUE
                          TRUE         TRUE        FALSE       TRUE    FALSE
                          TRUE         TRUE        TRUE     TRUE    TRUE
                          TRUE       TRUE        TRUE     TRUE    TRUE
                          TRUE       TRUE        TRUE     TRUE    TRUE")
which(df == FALSE, arr.ind = TRUE)[,2] #gives you the col numbers

The argument arr.ind, if True, gives you the array indices from which you can extract the column numbers

like image 75
Nico Avatar answered Oct 17 '25 03:10

Nico


You can use the following solution:

library(dplyr)

df %>%
  select(where(~ any(. == FALSE))) %>%
  names()

[1] "Species" "Time"  
like image 32
Anoushiravan R Avatar answered Oct 17 '25 04:10

Anoushiravan R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!