0
我有一個包含4行的數據框。我來總結當前行值和同一列的前一行值,而應該重複,直到塔頂部如何使用R中的sapply在每一行上重複使用函數
aa<-data.frame(groupid=c(0:3),var=rep(10,4))
>aa
groupid var
0 10
1 10
2 10
3 10
#if iterating over only 4th row
>i=4
#What I want to achieve->
>for(x in 1:aa$groupid[i]) {
aa$var[i]<-aa$var[i]+aa$var[i-x]
}
>aa$var[i]
40 #aa$var[4]+aa$var[3]+aa$var[2]+aa$var[1]
#How I want to achieve--> using sapply() as my real data frame is huge and
#for loop is taking a lot of time
#What I have achieved till now-->
>bb<-sapply(aa$groupid[i], function(x){
sum(aa$var[i],aa$var[i-x])
})
>bb
20 #aa$var[4]+aa$var[3]
如何遍歷從底部每排sapply(頂部)爲它重新保存在同一個變量中的值?
我得到了答案!謝謝! – Riya