我有一个数据框,我想使用mutate填充"e_value"列,这是"e" metric within 一个组的值,所以我使用dplyr和group_by组然后使用值[metric == "e"]进行变异,但这是如果在组C中没有指标== 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"] )
2 回答
您可以插入
ifelse
以使其成为条件 .或者像这样使用
%in%
: