[英]Create new variable using mutate on logical conditions across many variables - mutate?
Can mutate
create new variables based on logical conditions applied across variables? mutate
可以根据跨变量应用的逻辑条件创建新变量吗?
More specifically, consider the following data. 更具体地说,请考虑以下数据。
set.seed(1234)
val <- c(rep(0, 20), 1)
a <- sample(val, 50, replace=T)
b <- sample(val, 50, replace=T)
c <- sample(val, 50, replace=T)
d <- sample(val, 50, replace=T)
dat <- data.frame(a,b,c,d)
Here is some pseudo-code that gets at what I would like to do, but essentially removing all the logical comparisons (because I have a lot to make). 这里有一些伪代码可以实现我想做的事情,但基本上删除了所有的逻辑比较(因为我有很多东西要做)。 Obviously this is not functional code.
显然这不是功能代码。
new.dat <- mutate(dat, anyABCD == ifelse(A or B or C or D == 1, 1, 0))
Is there a more efficient procedure for handling this task to avoid a very long set of ifelse conditionals? 是否有更有效的程序来处理此任务以避免一长串ifelse条件? I found a similar question here but I want to apply one single logical comparison rather than writing each one out.
我在这里发现了一个类似的问题但是我想应用一个单一的逻辑比较而不是写出每一个。 I could not figure out how to make the subsequent code work using
data.table
. 我无法弄清楚如何使用
data.table
使后续代码工作。 Any help would be greatly appreciated! 任何帮助将不胜感激!
As always, the optimal answer is going to depend on the specific question. 与往常一样,最佳答案取决于具体问题。
In this case, for example, you can use pmax()
: 在这种情况下,例如,您可以使用
pmax()
:
dat$anyABCD <- with(dat, pmax(a, b, c, d) == 1)
head(dat)
a b c d anyABCD
1 0 0 0 0 FALSE
2 0 0 0 0 FALSE
3 0 0 0 0 FALSE
4 0 0 0 0 FALSE
5 0 0 0 0 FALSE
6 0 0 0 1 TRUE
You can also use an apply
function, for example: 您还可以使用
apply
函数,例如:
dat$anyABCD <- apply(dat[, 1:4], 1, function(x)max(x) == 1)
head(dat)
a b c d anyABCD
1 0 0 0 0 FALSE
2 0 0 0 0 FALSE
3 0 0 0 0 FALSE
4 0 0 0 0 FALSE
5 0 0 0 0 FALSE
6 0 0 0 1 TRUE
And, if you are quite certain that your data is binary, you can use rowSums()
: 而且,如果您确定数据是二进制的,则可以使用
rowSums()
:
dat$anyABCD <- rowSums(dat[, 1:4] >= 1)
head(dat)
a b c d anyABCD
1 0 0 0 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.