2

有没有办法将命名变量和包含带空格的变量名的对象都传递给ddply?这是我的意思的一个例子:

> library(plyr)
> dat <- data.frame(id1=rep(c("A","B"),8),id2=rep(c("C","D","E","F"),4),x=rnorm(16))
> vname <- "id2"
#works without spaces
> ddply(dat,c("id1",vname),colwise(sum))
  id1 id2          x
1   A   C -1.1215505
2   A   E -1.4507586
3   B   D  1.5064013
4   B   F -0.5428153
> vname <- "id 2"
> names(dat)[2] <- vname
#breaks with spaces
> ddply(dat,c("id1",vname),colwise(sum))
Error in parse(text = x) : <text>:1:4: unexpected numeric constant
1: id 2
      ^
#backticks work when manually entering the name
> ddply(dat,c("id1","`id 2`"),colwise(sum))
  id1 id 2          x
1   A    C -1.1215505
2   A    E -1.4507586
3   B    D  1.5064013
4   B    F -0.5428153
#backticks don't work when pointing to object containing name
> ddply(dat,c("id1",`vname`),colwise(sum))
Error in parse(text = x) : <text>:1:4: unexpected numeric constant
1: id 2
      ^
4

2 回答 2

2

您不能指望非语法名称可以很好地与所有函数和包一起使用。

但是,他们将与data.table,

改为使用data.table。相当于colwise(fun)lapply(.SD, fun)

  dat <- data.frame(id1=rep(c("A","B"),8),
          "id 2"=rep(c("C","D","E","F"),4),x=rnorm(16), check.names= FALSE)

  library(data.table)
  DT <- data.table(dat)
  vname <- "id 2"
  DT[,lapply(.SD, sum) , by = c('id1',vname)]

如果你想坚持plyr

然后

as.character(as.name(vname))

将创建字符向量

您可以创建一个执行此操作的函数

charN <- function(x) as.character(as.name(x))
于 2013-03-14T22:10:48.620 回答
2

你可以这样做,但它看起来很丑:

 ddply(dat,c("id1",paste("`",vname,"`",sep='')),colwise(sum))
  id1 id 2          x
1   A    C  1.3719443
2   A    E -0.3264330
3   B    D -0.3231757
4   B    F -0.6807928

正如评论中所说,使用格式正确的名称。

于 2013-03-14T20:42:10.670 回答