Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206180

Is there way to calculate multiple new rows of a data frame based on previous rows' values?

$
0
0

I am creating a data frame (hoops) with three columns (t, x, y) and 700 rows. See code at bottom. In the first row, I have set column t to equal 0. In the second row, I want to have the column t be calculated by taking the previous row's t value and add a constant (hoops_var). I want this to formula to continue to row 700.

hoops<-data.frame(t=double(),x=double(),y=double())

hoops_var<- 1.5

hoops[1,1]<- 0
hoops[1,2]<- (hoops$t+23)
hoops[1,3]<- (hoops$t/2)

# What I want for row 2
hoops[2,1]<- hoops[[1,1]]+hoops_var #this formula for rows 2 to 700
hoops[2,2]<- (hoops$t+23) #same as row 1
hoops[2,2]<- (hoops$t/2) #same as row 1

# What I want for row 3 to 700 (same as row 2)
hoops[3:700,1]<- hoops[[2,2]]+hoops_var #same as row 2
hoops[3:700,2]<- (hoops$t+23) #same as rows 1 & 2
hoops[3:700,3]<- (hoops$t/2) #same as row 1 & 2

The first four rows of the table should look like this

enter image description here

The only applicable solution I found (linked at bottom) did not work for me.

I am fairly new to R, so apologies if this is a dumb question. Thanks in advance for any help.

R: Creating a new row based on previous rows


Viewing all articles
Browse latest Browse all 206180

Trending Articles