Is there a way to pass both named variables and an object containing a variable name with spaces into ddply? Here is an example of what I mean:
> 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
^
You can do this , but it looks UGLY:
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
as said in the comment USE properly formatted name.
You can't expect non-syntatic names to work nicely with all functions and packages.
They will, however, work with data.table
,
Use data.table
instead. The equivalent of colwise(fun)
is 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)]
If you wanted to stick with plyr
then
as.character(as.name(vname))
will create the character vector
You could create a function that did this
charN <- function(x) as.character(as.name(x))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.