我有一个大型数据集,除了每个第五行,我想要获取每行的值减去下一行。使用for循环,它非常简单,但是使用我的大型数据集,它需要一个多小时。我被告知应用函数的速度要快得多,但我不知道如何编写复杂的函数,我也找不到类似问题的例子。
#set up matrix
x=matrix(0,15,2)
x[,1]=c(1, 5, 4, 3, 4, 2, 4, 3, 7, 8, 3, 2, 9, 7, 3)
#run for loop
for (i in c(0:((nrow(x)/5)-1)*5)){
x[i+1,2]<-x[i+1,1]-x[i+2,1]
x[i+2,2]<-x[i+2,1]-x[i+3,1]
x[i+3,2]<-x[i+3,1]-x[i+4,1]
x[i+4,2]<-x[i+4,1]-x[i+5,1]
x[i+5,2]<-x[i+5,1]
}
我使用apply已经达到了这个目标,但它甚至没有像我想象的那样工作......
apply(x, FUN=function(i) x[i]-x[i+1], MARGIN=1)
编辑:我想出了如何使用for循环中的if ... else ...语句使for循环不同,这可能是编写函数的一步。
for (i in 1:nrow(x)){
if (i%%5==0){# for those rows that are a multiple of five
x[i,2]<-x[i,1]
}else{ # for all other rows
x[i,2]<-x[i,1]-x[i+1,1]
}
}
答案 0 :(得分:3)
您可以使用矢量化计算执行此操作。如果您使用nrow(x)
而不是15
,则会进行扩展。
# set up indexes for the 5, 10, ...
index.fifth<-seq(5,15,5)
# set up indexes for 1:4,6:9,11:14,...
# basically delete the ones for every fifth one
index.rest<-seq(1:15)[-index.fifth]
# calculate subtractions first
x[index.rest,2]<-x[index.rest,1]-x[index.rest+1,1]
# set 5, 10, ... to their values
x[index.fifth,2]<-x[index.fifth,1]