【问题标题】:dplyr: passing variable as parameters to functiondplyr:将变量作为参数传递给函数
【发布时间】:2021-06-14 14:22:23
【问题描述】:

我编写了一个函数来收集从宽格式到长格式的一些数据。我需要多次这样做,因此想编写一个函数来完成它。这是我的功能:

longFormat <- function(df, var){

  dflong <- df %>%
    gather(key = CONDITION, value = var, contains(var))

  dflong
}

如果我像这样传递参数'coltype_a':

newdf <- longFormat(dfwide, 'coltype_a')

然后生成的数据框是正确的,因为函数已查找列名中包含'coltype_a' 的所有列,amd 已将它们转换为长格式。但是,我希望函数将值列命名为 'coltype_a',但将列命名为 'var'。有谁知道如何让 dplyr 接受我给函数LongFormat 的参数并将其分配给gather 函数中的值?

非常感谢!

【问题讨论】:

    标签: r function dplyr


    【解决方案1】:

    我们可以使用!!

    longFormat <- function(df, var){
    
      dflong <- df %>%
        gather(key = CONDITION, value = !!var, contains(var))
    
      dflong
    }
    

    -测试

    head(longFormat(iris, 'Species'))
       Sepal.Length Sepal.Width Petal.Length Petal.Width CONDITION Species
    1          5.1         3.5          1.4         0.2   Species  setosa
    2          4.9         3.0          1.4         0.2   Species  setosa
    3          4.7         3.2          1.3         0.2   Species  setosa
    4          4.6         3.1          1.5         0.2   Species  setosa
    5          5.0         3.6          1.4         0.2   Species  setosa
    6          5.4         3.9          1.7         0.4   Species  setosa
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多