dplyr 使用条件值进行变异 [英] dplyr mutate with conditional values
问题描述
在包含四列的大型数据框(myfile")中,我必须添加第五列,其中的值基于前四列有条件.
In a large dataframe ("myfile") with four columns I have to add a fifth column with values conditionally based on the first four columns.
首选 dplyr
和 mutate
的答案,主要是因为它在大型数据集中的速度.
Prefer answers with dplyr
and mutate
, mainly because of its speed in large datasets.
我的数据框如下所示:
V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4
...
第五列 (V5) 的值基于一些条件规则:
The values of the fifth column (V5) are based on some conditional rules:
if (V1==1 & V2!=4) {
V5 <- 1
} else if (V2==4 & V3!=1) {
V5 <- 2
} else {
V5 <- 0
}
现在我想使用 mutate
函数在所有行上使用这些规则(以避免慢循环).像这样的东西(是的,我知道这样不行!):
Now I want to use the mutate
function to use these rules on all rows (to avoid slow loops). Something like this (and yes, I know it doesn't work this way!):
myfile <- mutate(myfile, if (V1==1 & V2!=4){V5 = 1}
else if (V2==4 & V3!=1){V5 = 2}
else {V5 = 0})
这应该是结果:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
如何在 dplyr
中做到这一点?
How to do this in dplyr
?
推荐答案
试试这个:
myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
给予:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
或者这个:
myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
给予:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
注意
建议您为数据框取一个更好的名称.myfile 使它看起来好像包含一个文件名.
Note
Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.
上面使用了这个输入:
myfile <-
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L,
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
更新 1 由于最初发布的 dplyr 已将 %.%
更改为 %>%
,因此相应地修改了答案.
Update 1 Since originally posted dplyr has changed %.%
to %>%
so have modified answer accordingly.
更新 2 dplyr 现在有 case_when
,它提供了另一种解决方案:
Update 2 dplyr now has case_when
which provides another solution:
myfile %>%
mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1,
V2 == 4 & V3 != 1 ~ 2,
TRUE ~ 0))
这篇关于dplyr 使用条件值进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!