- [R - 在新列上,如何复制每个行?

我想要复制每个唯一的id行13,并创建一个新列,其中包含值从-8 to 4来填充以前的行,

示例数据:


data <- data.frame(id = seq(1,100,1),


 letters = sample(c("A","B","C","D"), replace = TRUE))



> head(data)


 id letters


1 1 A


2 2 B


3 3 B


4 4 C


5 5 A


6 6 B



预期的数据:


 newcol id letters


1 -8 1 A


2 -7 1 A


3 -6 1 A


4 -5 1 A


5 -4 1 A


6 -3 1 A


7 -2 1 A


8 -1 1 A


9 0 1 A


10 1 1 A


11 2 1 A


12 3 1 A


13 4 1 A


14 -8 2 B


15 -7 2 B


16 -6 2 B


17 -5 2 B



时间:

我们可以用uncount


library(tidyr)


library(dplyr)


data %>%


 uncount(13) %>%


 group_by(id) %>%


 mutate(newcol = -8:4) %>%


 ungroup



或在base R


data1 <- data[rep(seq_len(nrow(data)), each = 13),]


data1$newcol <- -8:4



或者使用data.table


library(data.table)


setDT(data)[rep(seq_len(.N), each = 13)][, newcol := rep(-8:4, length.out = .N)][]



...