【发布时间】:2015-08-08 08:56:59
【问题描述】:
我有一个这样的data.frame:
n = 50
df = data.frame(group=sample(1:as.integer(n/2),n,replace=T),
x = runif(n),
y = runif(n),
z = runif(n))
df = df[with(df,order(group)),]
对于group 的每个唯一值,我需要做的是生成段,即生成新列的位置,xend、yend 和zend,它们是x, y, z 该组中前一个点的值。对于组中的最后一个值,将端点作为组中的第一个点。
我可以通过以下方式做到这一点:
res = ddply(df,"group",function(d){
ixc = c("x","y","z")
dfE = d[,ixc]
dfE = rbind(dfE[nrow(dfE),],dfE[1:(nrow(dfE)-1),])
colnames(dfE) = paste0(ixc,"end")
cbind(d,dfE)
})
print(head(res))
当n 很小时这很简单,但是当n 变大时,执行上述操作的时间变得很重要,有没有更快的方法来做到这一点,也许使用data.table?
【问题讨论】:
标签: r data.table plyr