首页 文章

在mutate中粘贴变量名(dplyr)

提问于
浏览
0

我尝试在mutate_()函数(dplyr)中使用paste()创建变量 .

我尝试用这个答案(dplyr - mutate: use dynamic variable names)调整代码,但它不起作用......

NB: nameVarPeriod1 is a param of a function .

nameVarPeriod1=A2
df <- df %>%
    group_by(segment) %>%
    mutate_((.dots=setNames(mean(paste0("Sum",nameVarPeriod1)), paste0("MeanSum",nameVarPeriod1))))

这会返回一个警告:

Warning message:
In mean.default(paste0("Sum", nameVarPeriod1)) :
  argument is not numeric or logical: returning NA

如何评估paste0中的字符串作为变量名?

当我用这个替换paste0时它工作正常:

df <- df %>%
    group_by(segment) %>%
    mutate(mean=mean(SumA2))

DATA :

structure(list(segment = structure(c(5L, 1L, 4L, 2L, 2L, 14L, 
11L, 6L, 14L, 1L), .Label = c("Seg1", "Seg2", "Seg3", "Seg4", 
"Seg5", "Seg6", "Seg7", "Seg8", "Seg9", "Seg10", "Seg11", "Seg12", 
"Seg13", "Seg14"), class = "factor"), SumA2 = c(107584.9, 127343.87, 
205809.54, 138453.4, 24603.46, 44444.39, 103672, 88695.8, 64400, 
36815.82)), .Names = c("segment", "SumA2"), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

2 回答

  • 5

    dplyr 0.7.0 以后不需要使用 mutate_ . 这是一个使用 := 动态分配变量名和辅助函数的解决方案 quo name .

    有关详细信息,请阅读 vignette("programming", "dplyr") 会很有帮助 . 有关旧版本的dplyr,另请参阅dplyr - mutate: use dynamic variable names .

    df <- df %>%
      group_by(segment) %>%
      mutate( !!paste0('MeanSum',quo_name(nameVarPeriod1)) := 
    mean(!!as.name(paste0('Sum',quo_name(nameVarPeriod1)))))
    
  • 2

    不确定使用原始列名重命名汇总列名称的目的是什么 . 但是,如果您正在寻找一个解决方案,您想拥有多列的 sum ,因此想要重命名那些 dplyr::mutate_at 为您做到了 .

    library(dplyr)
    df %>% group_by(segment) %>%
      mutate(SumA3 = SumA2) %>%     #Added another column to demonstrate 
      mutate_at(vars(starts_with("SumA")), funs(mean = "mean"))
    
    #  segment  SumA2  SumA3 SumA2_mean SumA3_mean
    # <fctr>   <dbl>  <dbl>      <dbl>      <dbl>
    # 1 Seg5    107585 107585     107585     107585
    # 2 Seg1    127344 127344      82080      82080
    # 3 Seg4    205810 205810     205810     205810
    # 4 Seg2    138453 138453      81528      81528
    # 5 Seg2     24603  24603      81528      81528
    # 6 Seg14    44444  44444      54422      54422
    # 7 Seg11   103672 103672     103672     103672
    # 8 Seg6     88696  88696      88696      88696
    # 9 Seg14    64400  64400      54422      54422
    # 10 Seg1     36816  36816      82080      82080
    

相关问题