在R:dcast函数中,传递列名称(再次!)

use*_*672 4 arguments casting r function reshape2

鉴于半长的格式ID为变量DF ab和测定在列中的数据m1m2.数据类型由变量指定v(值var1和var2).

set.seed(8)

df_l <- 
  data.frame(
    a = rep(sample(LETTERS,5),2),
    b = rep(sample(letters,5),2),
    v = c(rep("var1",5),rep("var2",5)),
    m1 = sample(1:10,10,F),
    m2 = sample(20:40,10,F)) 
Run Code Online (Sandbox Code Playgroud)

看起来像:

   a b    v m1 m2
1  W r var1  3 40
2  N l var1  6 32
3  R a var1  9 28
4  F g var1  5 21
5  E u var1  4 38
6  W r var2  1 35
7  N l var2  8 33
8  R a var2 10 29
9  F g var2  7 30
10 E u var2  2 23
Run Code Online (Sandbox Code Playgroud)

如果我想在列中m1使用id a作为行和值来创建宽格式的值,v1我会这样做:

> reshape2::dcast(df_l, a~v, value.var="m1")
  a var1 var2
1 E    4    2
2 F    5    7
3 N    6    8
4 R    9   10
5 W    3    1
Run Code Online (Sandbox Code Playgroud)

如何编写一个函数来执行此操作dcast(row,column和value.var)的参数作为参数提供,类似于:

fun <- function(df,row,col,val){
  require(reshape2)
  res <-
    dcast(df, row~col, value.var=val)
  return(res)
}
Run Code Online (Sandbox Code Playgroud)

在这里这里检查了SO 以尝试变体match.calleval(substitute())为了"获取"函数内部的参数,并尝试使用lazyeval包.没有成功.

我在这做错了什么?如何让dcast识别变量名?

Aru*_*run 10

公式参数也接受字符输入.

foo <- function(df, id, measure, val) {
    dcast(df, paste(paste(id, collapse = " + "), "~", 
                    paste(measure, collapse = " + ")), 
          value.var = val)
}

require(reshape2)
foo(df_l, "a", "v", "m1")
Run Code Online (Sandbox Code Playgroud)

需要注意的是data.tabledcast(目前发展)也可以投多个value.var直接列.所以,你也可以这样做:

require(data.table) # v1.9.5
foo(setDT(df_l), "a", "v", c("m1", "m2"))
#    a m1_var1 m1_var2 m2_var1 m2_var2
# 1: F       1       6      28      21
# 2: H       9       2      38      29
# 3: M       5      10      24      35
# 4: O       8       3      23      26
# 5: T       4       7      31      39
Run Code Online (Sandbox Code Playgroud)