【发布时间】:2018-07-12 09:20:43
【问题描述】:
我有一个数据框,我想使用 mutate 填充一个“e_value”列,该列是“e”指标的值within组,所以我使用 dplyr 和 group_by group 然后使用 value[metric == "e"] 进行变异,但是当组内没有 metric == e 时,这将返回错误,如下面的组 C 中所示。当没有 e 指标时,有没有办法只返回 f 指标?
library(dplyr)
# this code does not work because there is no e metric in group C
data =data.frame(group = c("A","A","B","B","C"),metric=c("e","f","e","f","f"),value = c(1,2,3,4,5))
data %>% group_by(group) %>% mutate( e_value = value[metric == "e"] )
## this code below work becuase there is always an e metric
data =data.frame(group = c("A","A","B","B"),metric=c("e","f","e","f"),value = c(1,2,3,4))
data %>% group_by(group) %>% mutate( e_value = value[metric == "e"] )
【问题讨论】:
-
第一个示例的预期输出是什么?
-
这是你想要的吗:
data %>% group_by(group) %>% filter(metric == "e")?