davidbaseball
davidbaseball

Reputation: 27

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

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

Upvotes: 0

Views: 58

Answers (2)

fmarm
fmarm

Reputation: 4284

You should use vectorized operations

# first create all columns as vectors
hoops_t <- hoops_var*(0:699) #0:699 gives a vector of 700 consecutive integers
hoops_x <-  hoops_t+23
hoops_y <-  hoops_t/2

# now we are ready to put all vectors in a dataframe
hoops <- data.frame(t=hoops_t,x=hoops_x,y=hoops_y)

Now if you want to change the t column you can use lag from dplyr to shift all values for example

library(dplyr)
hoops$t[2:nrow(hoops)] <- lag(hoops$x*hoops$y)[2:nrow(hoops)]

I select only [2:nrow(hoops)] (all rows except the first one) because you don't want the first row to be modified

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389335

You could use the following :

n <- 10 #Number of rows in the data.frame
t <- seq(0, by = 1.5, length.out = n)
x <- 23 + t
y <- t/2
hoops <- data.frame(t, x, y)
hoops #Sample for 10 rows.

#      t    x    y
#1   0.0 23.0 0.00
#2   1.5 24.5 0.75
#3   3.0 26.0 1.50
#4   4.5 27.5 2.25
#5   6.0 29.0 3.00
#6   7.5 30.5 3.75
#7   9.0 32.0 4.50
#8  10.5 33.5 5.25
#9  12.0 35.0 6.00
#10 13.5 36.5 6.75

Upvotes: 0

Related Questions