我有以下数据框:
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
Run Code Online (Sandbox Code Playgroud)
我想创建一个额外的列,比如f,使用以下逻辑:
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.
Run Code Online (Sandbox Code Playgroud)
在这个例子中输出将是
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
Run Code Online (Sandbox Code Playgroud)
用这个:
DF$f <- apply(DF, 1, function(x)(all(x) || all(!x)))
Run Code Online (Sandbox Code Playgroud)
其中"DF"是您的数据帧.
或者,利用logical值只是0s和1s算术的事实:
rowMeans(dat) %in% 0:1
[1] FALSE FALSE FALSE FALSE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)