Colwise吃ddply中的列名
问题描述:
我试图通过数据框分块,找到子数据框不平衡的情况下,并为缺少的因素的某些级别添加0值。为此,在ddply中,我快速比较了一个因子应该在哪个级别的集合向量,然后创建一些新行,复制子数据集的第一行但修改它们的值,然后对它们进行rbinding到旧的数据集。Colwise吃ddply中的列名
我使用colwise来执行复制。
这在ddply以外很好用。在ddply里面...识别行被吃掉了,并且在我的上面咬了一下。这是好奇的行为。看到下面的代码与抛出一些调试打印语句,看看结果的差异:
#a test data frame
g <- data.frame(a=letters[1:5], b=1:5)
#repeat rows using colwise
rep.row <- function(r, n){
colwise(function(x) rep(x, n))(r)
}
#if I want to do this with just one row, I get all of the columns
rep.row(g[1,],5)
是好的。它打印
a b
1 a 1
2 a 1
3 a 1
4 a 1
5 a 1
#but, as soon as I use ddply to create some new data
#and try and smoosh it to the old data, I get errors
ddply(g, .(a), function(x) {
newrows <- rep.row(x[1,],5)
newrows$b<-0
rbind(x, newrows)
})
这给
Error in rbind(deparse.level, ...) :
numbers of columns of arguments do not match
你可以看到问题与此调试版本
#So, what is going on here?
ddply(g, .(a), function(x) {
newrows <- rep.row(x[1,],5)
newrows$b<-0
print(x)
print("\n\n")
print(newrows)
rbind(x, newrows)
})
可以看出,x和newrows有不同的列 - 他们的不同。
a b
1 a 1
[1] "\n\n"
b
1 0
2 0
3 0
4 0
5 0
Error in rbind(deparse.level, ...) :
numbers of columns of arguments do not match
这是怎么回事?为什么当我在子数据框上使用colwise时,识别的行会被吃掉?
答
这似乎是ddply和colwise之间的一个有趣的互动。更具体地说,当colwise
调用strip_splits
并发现ddply
给出的vars
属性时,会发生此问题。
作为一种变通方法,尝试把这个第一行中的功能,
attr(x, "vars") <- NULL
# your code follows
newrows <- rep.row(x[1,],5)