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
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.
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.
The function unite() takes multiple columns and paste them together into one.
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.
Use this:
DF$f <- apply(DF, 1, function(x)(all(x) || all(!x)))
where "DF" is your dataframe.
Alternatively, exploiting the fact that logical
values are just 0
s and 1
s for arithmetic:
rowMeans(dat) %in% 0:1
[1] FALSE FALSE FALSE FALSE TRUE TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With