我有自己的解决方案来解决我的问题,但它涉及循环并且相对较慢.有什么方法可以更快地在R中使用 - 使用一些更高级的包?谢谢!
# My data frame:
d <- data.frame(ID=1:10,a = 1:10,b = 5:14)
# Desired number of repeats for each row:
freq = c(2,2,3,3,3,4,5,5,5,6)
# i.e., Raw 1 of d should be repeated 2 times
# Raw 10 of d should be repeated 6 times.
# My current solution - looping through unique values of freq:
d.long<-NULL
myrepeats=unique(freq)
for(i in myrepeats){
onecount<-d[freq==i,]
for(ii in 2:i){
temp<-d[freq==i,]
onecount<-rbind(onecount,temp)
}
d.long<-rbind(d.long,onecount)
}
d.long<-d.long[order(d.long$ID),]
(d.long)
Run Code Online (Sandbox Code Playgroud)
kai*_*kai 11
您可以使用重复索引:
d.long <- d[rep(1:nrow(d), times=freq),]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1516 次 |
| 最近记录: |