ddply +汇总功能列名称输入 [英] ddply + summarise function column name input
问题描述
我正在尝试从plyr
包中一起使用ddply
和summarise
,但是在解析不断变化的列名时遇到了困难...在我的示例中,我希望以编程方式在X1中进行解析比在X1中将硬编码编码到ddply函数中.
I am trying to use ddply
and summarise
together from the plyr
package but am having difficulty parsing through column names that keep changing...In my example i would like something that would parse in X1 programatically rather than hard coding in X1 into the ddply function.
设置示例
require(xts)
require(plyr)
require(reshape2)
require(lubridate)
t <- xts(matrix(rnorm(10000),ncol=10), Sys.Date()-1000:1)
t.df <- data.frame(coredata(t))
t.df <- cbind(day=wday(index(t), label=TRUE, abbr=TRUE), t.df)
t.df.l <- melt(t.df, id.vars=c("day",colnames(t.df)[2]), measure.vars=colnames(t.df)[3:ncol(t.df)])
这是我在努力挣扎的一点....
This is the bit im am struggling with....
cor.vars <- ddply(t.df.l, c("day","variable"), summarise, cor(X1, value))
我不想使用术语X1,而是想使用
i do not want to use the term X1 and would like to use something like
cor.vars <- ddply(t.df.l, c("day","variable"), summarise, cor(colnames(t.df)[2], value))
但是出现错误:Error in cor(colnames(t.df)[2], value) : 'x' must be numeric
我还尝试了其他各种组合,这些组合分析了cor中x参数的向量值...但是由于某些原因,它们似乎都不起作用...
I also tried various other combos that parse in the vector values for the x argument in cor...but for some reason none of them seem to work...
有什么想法吗?
推荐答案
尽管这可能不是summarize
的预期用法,并且必须有更好的解决方法,但直接的问题答案是使用get
:
Although this is probably not the intended usage for summarize
and there must be much better approaches to your problem, the direct answer to your question is to use get
:
ddply(t.df.l, c("day","variable"), summarise, cor(get(colnames(t.df)[2]), value))
例如,在我看来,这是一种更适合您的问题的方法:
here is for example one approach that is in my opinion better suited to your problem:
ddply(t.df.l, c("day", "variable"), function(x)cor(x["X1"], x["value"]))
以上,"X1"
也可以替换为2
或包含"X1"
的变量的名称,依此类推.这取决于您要如何以编程方式访问该列.
Above, "X1"
can be also replaced by 2
or the name of a variable holding "X1"
, etc. It depends how you want to programmatically access the column.
这篇关于ddply +汇总功能列名称输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!