如何在 dcast (reshape2) 的公式参数中使用列名的字符向量

How to use a character vector of column names in the formula argument of dcast (reshape2)

假设我有一个数据框 df,其中包含许多标识变量(在列中)和只有几个测量变量(也在列中)。

为了避免为每个参数重复键入所有变量,我将识别和测量的 df 列的名称分别分配给 df_iddf_measured。输入这些向量以缩短 melt...

的参数输入非常容易
df.m  <- melt(df, id.vars = df_id, measure.vars = df_measured)

...但是我不知道如何使用相同的方法在 dcast 中输入 formula = 参数来指定我的 id 变量,因为它要求输入指向数字列的位置。

我是否必须制作类似于 df_id 的数字位置向量,如果我的输入列按顺序更改,我的程序可能会出现功能中断的风险,或者我可以通过名称引用它们并以某种方式仍然得到它在 formula = 争论中工作?谢谢。

您可以使用as.formula来构造公式。

这是一个例子:

library(reshape2)
## Example from `melt.data.frame`
names(airquality) <- tolower(names(airquality))
df_id <- c("month", "day")
aq <- melt(airquality, id = df_id)

## Constructing the formula
f <- as.formula(paste(paste(df_id, collapse = " + "), "~ variable"))

## Applying it....
dcast(aq, f, value.var = "value", fun.aggregate = mean)

从 Tidyverse 包 glue 导出的函数 glue() 使公式比使用 paste()。这是 glue() 的作用:

a <- 1
b <- 2
glue( "{a} + {b} = {a+b}." )

returns 字符串

1 + 2 = 3.

因此 glue() 逐字记录其参数,但用大括号替换名称和其他表达式。有关完整规范,请参阅上面的 link:glue() 有其他参数,包括更多字符串,一个提供查找变量的环境的参数,以及两个参数将大括号更改为其他定界符。就 dcast() 而言,它避免了必须与 paste() 一起使用的额外引号和逗号。这是一个示例,使用您的 table:

install.packages( "glue" )
library( glue )

library( data.table ) 

dt <- data.table( c1 = c( 1  , 1  , 1  , 2   , 2   , 2    )    
                , c2 = c( "A", "B", "C", "A1", "B1", "C1" )
                , c3 = c( 1  , 2  , 3  , 1   , 2   , 3    )
                )

f1 <- function( d, col_name1, col_name2, col_name3 ) {
  dcast( d, glue( "{col_name1} ~ {col_name3}" ), value.var = col_name2 )
}

f1( dt, "c1", "c2", "c3" )

这是它的输出(在 R 3.6.3 上):

> f1( dt, "c1", "c2", "c3" )
   c1  1  2  3
1:  1  A  B  C
2:  2 A1 B1 C1