首页 文章

dplyr mutate with null value

提问于
浏览
0

我有一个数据框,我想使用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 回答

  • 0

    您可以插入 ifelse 以使其成为条件 .

    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
    
  • 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
    

相关问题