R中是否可以根据前一行的值来计算数据帧的多个新行?

问题描述 投票:0回答:2

我正在创建一个具有三列(t,x,y)和700行的数据框(箍)。请参阅底部的代码。在第一行中,我将列t设置为等于0。在第二行中,我希望通过获取上一行的t值并添加一个常量(hoops_var)来计算列t。我希望此公式继续到第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

表的前四行[should look like this

我发现的唯一适用的解决方案(在底部链接)对我不起作用。

我对R相当陌生,如果这是一个愚蠢的问题,我们深表歉意。预先感谢您的帮助。

R: Creating a new row based on previous rows

r dataframe datatable formula rows
2个回答
1
投票

您应该使用向量化操作

# first create all columns as vectors
hoops_t <- hoops_var*(0:699) #0:699 fives 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)

0
投票

您可以使用以下各项:

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
© www.soinside.com 2019 - 2024. All rights reserved.