复制行并在原始行之前插入

时间:2018-07-09 04:51:25

标签: r duplicates data.table row

我有data.table,看起来像这样:

try<-data.table(Time=c(5,11,12,13,15,26), N=c(1,3,1,2,1,1), 
                 Est=c(0.9956140, 0.9824561, 0.9780702, 0.9692982, 0.9649123, 0.9605263))

 Time N       Est
    5 1 0.9956140
   11 3 0.9824561
   12 1 0.9780702
   13 2 0.9692982
   15 1 0.9649123
   26 1 0.9605263

我需要复制值大于1的行N并将其插入到原始行之前。例如,输出应为:

 Time N        Est
   5  1  0.9956140
  11  1         NA
  11  2         NA
  11  3  0.9824561
  12  1  0.9780702
  13  1         NA
  13  2  0.9692982
  15  1  0.9649123
  26  1  0.9605263

1 个答案:

答案 0 :(得分:2)

这里是一个选项,用于首先复制行,并将与'N'的duplicated元素相对应的'Est'元素从最后位置更改为NA

try1 <- try[rep(seq_len(.N), N)][, N1 := seq_len(.N), .(Time, rleid(N))][]
i1 <- try1[, .I[duplicated(N, fromLast = TRUE)], rleid(N)]$V1
try1[i1, Est := NA]

或者用复制的'Time'和join的'N'做一个sequence

try[try[, .(Time = rep(Time, N), N = sequence(N))], on = .(Time, N)]
#   Time N       Est
#1:    5 1 0.9956140
#2:   11 1        NA
#3:   11 2        NA
#4:   11 3 0.9824561
#5:   12 1 0.9780702
#6:   13 1        NA
#7:   13 2 0.9692982
#8:   15 1 0.9649123
#9:   26 1 0.9605263