0

I am attempting to extract the rowname that marking rows that contain a single TRUE value. Please see the following example.

                  Col1  Col2  Col3
Npat             FALSE  TRUE FALSE
Ttc30a1           TRUE FALSE FALSE
Gga1              TRUE  TRUE  TRUE
Gga3             FALSE FALSE FALSE
Gga2             FALSE FALSE  TRUE

I would like to extract the rownames of the rows containing a single unique "TRUE" value and retain information about which column the true value was in. The desired output might look like:

                   Col1  Col2  Col3
Npat             FALSE  TRUE FALSE
Ttc30a1           TRUE FALSE FALSE
Gga2             FALSE FALSE  TRUE

I attempted to use grep and -grep but couldn't get it recognize multiple values in multiple columns. I am sure there is a simple way to do this that I haven't been able to track down yet.

Paul
  • 656
  • 1
  • 8
  • 23

3 Answers3

2

You can simply treat booleans as if they were numeric. In base R:

df[with(df, Col1 + Col2 + Col3  == 1) ,]
989
  • 12,579
  • 5
  • 31
  • 53
hdkrgr
  • 1,666
  • 1
  • 12
  • 22
2

Or you could use rowSums(df)==1:

df1 <-read.table(text="Row  Col1  Col2  Col3
Npat             FALSE  TRUE FALSE
Ttc30a1           TRUE FALSE FALSE
Gga1              TRUE  TRUE  TRUE
Gga3             FALSE FALSE FALSE
Gga2             FALSE FALSE  TRUE",header=TRUE, row.names=1,stringsAsFactors=FALSE)

df1[rowSums(df1)==1,]

         Col1  Col2  Col3
Npat    FALSE  TRUE FALSE
Ttc30a1  TRUE FALSE FALSE
Gga2    FALSE FALSE  TRUE
Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56
1

somewhat similar approach: (more general solution)

use apply to sum row-wise.

df[apply(df,1,sum)==1,]
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69