【问题标题】:R function using previous rows in same and different columns?R函数使用相同和不同列中的前行?
【发布时间】:2019-04-18 15:44:34
【问题描述】:

从虹膜数据集开始:

我想创建一个新列 B,其中第 1 行的值是 Sepal.Length 的值,第 2 行的值:n = B 从上一行 +(当前行的 Sepal.length - Sepal .length 上一行)。 所以行 B1 = 5.1, B2=5.1+(4.9-5.1 ...

谢谢!

编辑:上述模式只是部分的:公式应该只适用于(当前行的 Sepal.length - 前一行的 Sepal.length)。根据总督的回答,以下代码适用于编辑后的问题:

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

【问题讨论】:

  • value for row 1 is the value of Sepal.Length and the values for rows 2:n = B from the previous row 在第 1 行之前没有上一行。n 是什么?
  • 第 1 行只是 Sepal.length 第 1 行。公式将从第 2 行开始。
  • 你需要head(iris) %&gt;% mutate(new = Sepal.Length + c(diff(Sepal.Length), 0))
  • 顺便说一句,5.1 + (4.9 - 5.1) -&gt; 4.9
  • 调用上一行PR和当前行CR。你想要PR + CR - PR = CR...?

标签: r


【解决方案1】:

这应该可行:

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 你说得对,我忘了补充

iris$B <- B

请注意,使用包 dplyr 和函数 mutate 可能有一种更优雅/更有效的方法。

【讨论】:

  • all(B == iris$Sepal.Length) 返回真。所以写iris$newcol = iris$Sepal.Length的路还很长
  • 根据总督的回答,以下代码适用于编辑后的问题:` MyDataSet
猜你喜欢
  • 1970-01-01
  • 2013-06-28
  • 2018-07-19
  • 2018-06-24
  • 2023-03-20
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
相关资源
最近更新 更多