Use function instead of for loop in R: substracting previous rows iteratively with exceptions

早过忘川 提交于 2019-12-07 12:01:23

You can do this with a vectorized calculation. This scales up if you use nrow(x) instead of 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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!