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

时间:2015-02-12 18:08:00

标签: r reshape2

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

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

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

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

我是否必须创建一个类似于df_id的数字位置向量,并且如果我的输入列按顺序更改,则可能会破坏我的程序的功能,或者我可以通过名称引用它们并以某种方式仍然可以使其工作在formula =参数中?谢谢。

2 个答案:

答案 0 :(得分:7)

您可以使用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)

答案 1 :(得分:0)

从Tidyverse软件包glue中导出的函数 glue()比使用 paste()更容易构建公式。这是 glue()的作用:

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

返回字符串

1 + 2 = 3.

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

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
相关问题