如何获得R数据帧中给定行中的值与所有后续行的总和?

时间:2023-02-02 07:19:45

I have the following dataframe:

我有以下数据帧:

  area    peri
1 4990 2791.90
2 7002 3892.60
3 7558 3930.66
4 7352 3869.32

It is produced by this code:

它由以下代码生成:

myData=(rock[1:3,c("area","peri")])
print(myData)

For every line in the data, I want to add the peri-value of each following line respectively. How do I do this? In other words:

对于数据中的每一行,我想分别添加每个后续行的周期值。我该怎么做呢?换一种说法:

Question: What code do I need to apply to myData in order to get this:

问题:为了得到这个,我需要将哪些代码应用于myData:

  area1  area2   periSUM
1  4990   7002   6684.5
2  4990   7558   6722.56
3  4990   7352   6661.22
4  7002   7558   7823.26
5  7002   7352   7761.92
6  7558   7352   7799.98

1 个解决方案

#1


2  

This can be done using a self join in SQL:

这可以使用SQL中的自联接来完成:

library(sqldf)
sqldf("select a.area as area1, b.area as area2, a.peri + b.peri as peri 
       from myData a join myData b on b.rowid > a.rowid")

giving:

  area1 area2    peri
1  4990  7002 6684.50
2  4990  7558 6722.56
3  4990  7352 6661.22
4  7002  7558 7823.26
5  7002  7352 7761.92
6  7558  7352 7799.98

Note

The input used in reproducible form is:

以可再现的形式使用的输入是:

Lines <- "
  area    peri
1 4990 2791.90
2 7002 3892.60
3 7558 3930.66
4 7352 3869.32"

myData <- read.table(text = Lines)

#1


2  

This can be done using a self join in SQL:

这可以使用SQL中的自联接来完成:

library(sqldf)
sqldf("select a.area as area1, b.area as area2, a.peri + b.peri as peri 
       from myData a join myData b on b.rowid > a.rowid")

giving:

  area1 area2    peri
1  4990  7002 6684.50
2  4990  7558 6722.56
3  4990  7352 6661.22
4  7002  7558 7823.26
5  7002  7352 7761.92
6  7558  7352 7799.98

Note

The input used in reproducible form is:

以可再现的形式使用的输入是:

Lines <- "
  area    peri
1 4990 2791.90
2 7002 3892.60
3 7558 3930.66
4 7352 3869.32"

myData <- read.table(text = Lines)