我编写了一个函数来收集一些从宽格式到长格式的数据。我需要多次执行此操作,因此想编写一个执行此操作的函数。这是我的功能:
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 函数中的值?
非常感谢!
答案 0 :(得分: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