Reputation: 696
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.
Upvotes: 0
Views: 143
Reputation: 1736
You can simply treat booleans as if they were numeric. In base R:
df[with(df, Col1 + Col2 + Col3 == 1) ,]
Upvotes: 2
Reputation: 16277
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
Upvotes: 2
Reputation: 11480
somewhat similar approach: (more general solution)
use apply
to sum row-wise.
df[apply(df,1,sum)==1,]
Upvotes: 1