简体   繁体   English

R中的回填数据框基于最大数量

[英]Backfill data frame in R based on maximum number

I have a data frame with a number of id's and max values. 我有一个数据框,其中包含许多id和max值。

df <- data.frame(id = c("a", "b", "c"), max.number = c(0, 6, 4))

  id max.number
1  a          0
2  b          6
3  c          4

I want to create a new data frame that backfills down to zero for each id. 我想创建一个新的数据框,为每个id回填到零。 It would look like: 它看起来像:

  id     number
1  a          0
2  b          0
3  b          1
4  b          2
5  b          3
6  b          4
7  b          5
8  b          6
9  b          0
10 c          1
11 c          2
12 c          3
13 c          4

I've tried to do this through a nested for loop but can't get it to work correctly. 我试图通过嵌套的for循环来做到这一点,但无法让它正常工作。 I would love some guidance in doing this with apply if possible. 如果可能的话,我希望通过申请来做一些指导。

This would be very easy with a data.table table: 使用data.table表这很容易:

# install.packages("data.table")
library(data.table)

df <- data.frame(id = c("a", "b", "c"), max.number = c(0, 6, 4))
dt <- as.data.table(df) 
# or directly: 
# dt <- data.table(id = c("a", "b", "c"), max.number = c(0, 6, 4))
dt[, .(number=seq(0, max.number)), by=id]

Output: 输出:

    id number
 1:  a      0
 2:  b      0
 3:  b      1
 4:  b      2
 5:  b      3
 6:  b      4
 7:  b      5
 8:  b      6
 9:  c      0
10:  c      1
11:  c      2
12:  c      3
13:  c      4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM