简体   繁体   中英

R function using previous rows in same and different columns?

Starting with the iris data set:

I want to create a new column B, where the value for row 1 is the value of Sepal.Length and the values for rows 2:n = B from the previous row +(Sepal.length of the current row - Sepal.length of the previous row). so row B1 = 5.1, B2=5.1+(4.9-5.1 ...

Thanks!

edit: The above described patter is only partial: the formula should only apply when (Sepal.length of the current row - Sepal.length of the previous row). Based on The Governor's answer, the code below works for the edited question:

MyDataSet<-data.frame(time=c(1,2,3,1,2,3)) 
B <- rep(NA,(nrow(MyDataSet))) 
B[1] <- MyDataSet$time[1] 

for (i in 2:nrow(MyDataSet)) { 
if (0<MyDataSet$time[i]-MyDataSet$time[i-1])
{B[i] <- B[i-1]+(MyDataSet$time[i]-MyDataSet$time[i-1]) }  
 else {B[i]<-B[i-1]+MyDataSet$time[i]} 
} 

MyDataSet$B <- B

This should work:

data(iris)

B <- rep(NA, (nrow(iris)))
B[1] <- iris$Sepal.Length[1]
for ( i in 2:nrow(iris)){
  B[i] <- B[i-1]+(iris$Sepal.Length[i]-iris$Sepal.Length[i-1])  
}

@Lina Bird you're right I forgot to add

iris$B <- B

Note that there may be a more elegant/efficient way to do this using the package dplyr and the function mutate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM