r - 如何优雅地计算 R data.frame 中使用前一行中的值的变量?

标签 r

这是我构建的一个简单场景:

假设我有以下内容:

set.seed(1)
id<-sample(3,10,replace = TRUE)
n<-1:10
x<-round(runif(10,30,40))
df<-data.frame(id,n,x)
df
   id  n  x
1   1  1 32
2   2  2 32
3   2  3 37
4   3  4 34
5   1  5 38
6   3  6 35
7   3  7 37
8   2  8 40
9   2  9 34
10  1 10 38

如何优雅地计算 x.lag,其中 x.lag 是同一 id 的前一个 x,如果前一个值不存在,则为 0。

这就是我所做的,但我对此不满意:

df$x.lag<-rep(0,10)
for (id in 1:3)
 df[df$id==id,]$x.lag<-c(0,df[df$id==id,]$x)[1:sum(df$id==id)]
df
   id  n  x x.lag
1   1  1 32     0
2   2  2 32     0
3   2  3 37    32
4   3  4 34     0
5   1  5 38    32
6   3  6 35    34
7   3  7 37    35
8   2  8 40    37
9   2  9 34    40
10  1 10 38    38

最佳答案

我们可以使用data.table

library(data.table)
setDT(df)[, x.lag :=  shift(x, fill=0), id]

或者使用dplyr

library(dplyr)
df %>%
  group_by(id) %>%
  mutate(x.lag = lag(x, default = 0))

或者使用base R中的ave

df$x.lag <- with(df, ave(x, id, FUN = function(x) c(0, x[-length(x)])))
df$x.lag
#[1]  0  0 32  0 32 34 35 37 40 38

关于r - 如何优雅地计算 R data.frame 中使用前一行中的值的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43773264/

相关文章:

r - 使用 tidyverse 对大型时间序列数据集有条件聚合列

r - 如何在 R 中的 ggplot2 中的瓷砖上放置标签?

r - 让 rbind 忽略列名的最简单方法

r - 将箱线图转换为 R 中 ggplot2 中的密度

r - R 包的 HTML 帮助页面中的数字(R 代码执行结果)

r - 如何将颜色匹配的图例添加到 R matplot

R- shiny-plotly 第二轴标签与 yaxis 值重叠

r - 当 cols = 以特定前缀开头的任何列时如何使用 tidyr pivot_longer

python - 从一个表中提取小时值并在另一个表中填充一小时增量的 "buckets"的函数

linux - Rscript 会改变 LD_LIBRARY_PATH 吗?