dplyr mutate with null value

时间:2018-02-01 22:56:03

标签: r dplyr

我有一个数据框,我想使用mutate填充“e_value”列,该列是指标组中的值,因此我使用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 个答案:

答案 0 :(得分:0)

您可以插入data %>% group_by(group) %>% mutate( e_value = ifelse(is.null(value[metric == "e"]), NA, value[metric == "e"]) ) # # A tibble: 5 x 4 # # Groups: group [3] # group metric value e_value # <fct> <fct> <dbl> <dbl> # 1 A e 1.00 1.00 # 2 A f 2.00 1.00 # 3 B e 3.00 3.00 # 4 B f 4.00 3.00 # 5 C f 5.00 NA 以使其成为条件。

{{1}}

答案 1 :(得分:0)

或者使用%in%

这样
data %>% group_by(group) %>% mutate(e_value = ifelse("e" %in% metric, value, NA));
## A tibble: 5 x 4
## Groups:   group [3]
#   group metric value e_value
#  <fctr> <fctr> <dbl>   <dbl>
#1      A      e     1       1
#2      A      f     2       1
#3      B      e     3       3
#4      B      f     4       3
#5      C      f     5      NA