【问题标题】:Use function instead of for loop in R: substracting previous rows iteratively with exceptions在 R 中使用函数而不是 for 循环:迭代地减去前面的行,但有异常
【发布时间】:2018-01-31 17:55:41
【问题描述】:

我有一个大型数据集,我想获取每行的值减去下一行的值,但每第五行除外。使用 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]
}
}

【问题讨论】:

    标签: r function for-loop apply


    【解决方案1】:

    您可以通过矢量化计算来做到这一点。如果您使用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]
    

    【讨论】:

    • 这比我想象的要简单得多!我没想过把它当作矩阵算术来对待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多