R 如何以一定的次数重复堆叠同一行

R 如何以一定的次数重复堆叠同一行,r,for-loop,R,For Loop,这个问题与下面的帖子有关,但是,这是一个更一般的问题 我有数据,反复观察ID1。值随着时间的推移而变化间隔是观察开始和观察停止的时间间隔 ID<-rep(1,4) start<-c(0, 1, 4, 5) stop<-c(1, 4, 5, 7) sex<-c("M","M","M","M") value<-c(10.5,20,13,19) test<-data.frame(ID,start,stop,sex,value) test<-test%>

这个问题与下面的帖子有关,但是,这是一个更一般的问题

我有数据,反复观察
ID
1。
值随着时间的推移而变化<代码>间隔
是观察开始和观察停止的时间间隔

ID<-rep(1,4)
start<-c(0, 1, 4, 5)
stop<-c(1, 4, 5, 7)
sex<-c("M","M","M","M")
value<-c(10.5,20,13,19)
test<-data.frame(ID,start,stop,sex,value)
test<-test%>%mutate(rep=stop-start)

  ID start stop sex value interval
1  1     0    1   M  10.5        1
2  1     1    4   M  20.0        3
3  1     4    5   M  13.0        1
4  1     5    7   M  19.0        2
第二列试验重复两次(3-1)并堆叠


我尝试了
循环,但它非常复杂。是否有一种方法可以使用
for
循环执行此操作?

我们可以使用
tidyr::uncount

tidyr::uncount(test, rep, .remove = FALSE)

#    ID start stop sex value rep
#1    1     0    1   M  10.5   1
#2    1     1    4   M  20.0   3
#2.1  1     1    4   M  20.0   3
#2.2  1     1    4   M  20.0   3
#3    1     4    5   M  13.0   1
#4    1     5    7   M  19.0   2
#4.1  1     5    7   M  19.0   2
或者在base R中,我们可以使用
rep

test[rep(1:nrow(test), test$rep), ]
test[rep(1:nrow(test), test$rep), ]