在R

时间:2017-08-02 18:23:06

标签: r

我的数据包含三个变量。有三个唯一ID,每个ID都有多个记录。

ID <- c(rep(1,2), rep(2,1), rep(3,2))
y0 <- c(rep(5,2), rep(3,1), rep(1,2))
z0 <- c(rep(1,2), rep(13,1), rep(4,2))

dat1 <- data.frame(ID, y0,z0)

我想要的是重复整个数据N次(N需要是一个参数),我需要添加一个带有重复数的新列。

因此,如果N = 2,则新数据如下所示:

rep <- c(rep(1,2), rep(2,2), rep(1,1), rep(2,1), rep(1,2), rep(2,2))
ID <- c(rep(1,4), rep(2,2), rep(3,4))
y0 <- c(rep(5,4), rep(3,2), rep(1,4))
z0 <- c(rep(1,4), rep(13,2), rep(4,4))

dat2 <- data.frame(rep, ID, y0,z0)

1 个答案:

答案 0 :(得分:1)

我们稍后复制行序列和order以获得预期的输出

res <- cbind(rep = rep(seq_len(2), each = nrow(dat1)), dat1[rep(seq_len(nrow(dat1)), 2),])
resN <- res[order(res$ID),]
row.names(resN) <- NULL
all.equal(dat2, resN, check.attributes = FALSE)
#[1] TRUE

或另一种选择是将replicate改为list,然后使用Map创建&#39; rep&#39;列(不建议将函数名称作为列名,对象名等)和rbind list元素

res1 <- do.call(rbind, Map(cbind, rep = seq_len(2), replicate(2, dat1, simplify = FALSE)))
res2 <- res1[order(res1$ID),]
row.names(res2) <- NULL
all.equal(dat2, res2, check.attributes = FALSE)
#[1] TRUE