排序固定次数

时间:2019-03-06 00:13:35

标签: r sequence

我要创建一个增量序列:

我有一个数据框 dt <- data.table(Customer = c("a", "b", "c"), count = c(3, 4, 5), ACV = c("30","20","30"))

     Customer count ACV
1:        a     3  30
2:        b     4  20
3:        c     5  30

我正在使用以下方法按计数复制此数据帧: {dt[rep(seq(1, nrow(dt)), dt$count)]}

我收到的输出是

    Customer count ACV
 1:        a     3  30
 2:        a     3  30
 3:        a     3  30
 4:        b     4  20
 5:        b     4  20
 6:        b     4  20
 7:        b     4  20
 8:        c     5  30
 9:        c     5  30
10:        c     5  30
11:        c     5  30
12:        c     5  30

但是我希望ACV列增加1 ...因此,所需的输出是

    Customer count ACV
 1:        a     3  30
 2:        a     3  31
 3:        a     3  32
 4:        b     4  20
 5:        b     4  21
 6:        b     4  22
 7:        b     4  23
 8:        c     5  30
 9:        c     5  31
10:        c     5  32
11:        c     5  33
12:        c     5  34

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我们可以使用dplyr并将row_number()添加到组中的第一个ACV

new_dt <- dt[rep(seq(1, nrow(dt)), dt$count)]

library(dplyr)

new_dt %>% 
   group_by(Customer) %>%
   mutate(ACV = as.numeric(ACV[1]) + row_number() - 1)


#   Customer count   ACV
#   <chr>    <dbl> <dbl>
# 1 a            3    30
# 2 a            3    31
# 3 a            3    32
# 4 b            4    20
# 5 b            4    21
# 6 b            4    22
# 7 b            4    23
# 8 c            5    30
# 9 c            5    31
#10 c            5    32
#11 c            5    33
#12 c            5    34

在基数R中,我们可以使用ave并使用seq_along代替row_number

new_dt$ACV <- with(new_dt, ave(as.numeric(ACV), Customer, 
                   FUN = function(x) x[1] + seq_along(x)) - 1)

使用data.table我们可以做到

new_dt[, new_ACV := as.integer(ACV[1]) + seq_len(.N) - 1L, by = Customer]

答案 1 :(得分:0)

使用data.table语法的一种方法:

# example dataset with ACV as numeric
library(data.table)
dt <- data.table(Customer = c("a", "b", "c"), count = c(3, 4, 5), ACV = c(30,20,30))

# expand the number of rows according to "count"
dt <- dt[rep(1:.N, count)]

# increment ACV
dt[ , ACV := ACV + 1:.N - 1, by=Customer]