Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical vector with multiple columns in R

Tags:

r

I have te following dataframe:

a    b     c     d     e
TRUE TRUE FALSE  TRUE  TRUE
FALSE TRUE  TRUE  TRUE FALSE
TRUE TRUE FALSE  TRUE  TRUE
TRUE TRUE  TRUE FALSE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE

I would like to create an extra column , say f, with the following logic:

TRUE = If all the columns in the corresponding row are all TRUE or all FALSE.
FALSE = if one or more colums differ from the other columns in the corresponding row.

In this example the output would be

a    b     c     d     e     f
TRUE TRUE FALSE  TRUE  TRUE  FALSE
FALSE TRUE  TRUE  TRUE FALSE  FALSE
TRUE TRUE FALSE  TRUE  TRUE  FALSE
TRUE TRUE  TRUE FALSE  TRUE  FALSE
TRUE TRUE  TRUE  TRUE  TRUE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE  TRUE
like image 724
rwn1v Avatar asked Sep 09 '13 23:09

rwn1v


People also ask

How do I specify multiple columns in R?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.

Can you Group_by multiple columns in R?

How to perform a group by on multiple columns in R DataFrame? By using group_by() function from dplyr package we can perform group by on multiple columns or variables (two or more columns) and summarise on multiple columns for aggregations.

Can you gather multiple columns in R?

The function unite() takes multiple columns and paste them together into one.

What does across () do in R?

across() returns a tibble with one column for each column in . cols and each function in . fns . if_any() and if_all() return a logical vector.


2 Answers

Use this:

DF$f <- apply(DF, 1, function(x)(all(x) || all(!x)))

where "DF" is your dataframe.

like image 69
Ferdinand.kraft Avatar answered Oct 04 '22 05:10

Ferdinand.kraft


Alternatively, exploiting the fact that logical values are just 0s and 1s for arithmetic:

rowMeans(dat) %in% 0:1
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE
like image 45
thelatemail Avatar answered Oct 04 '22 04:10

thelatemail