Reputation: 27
I am looking to add rows to my data frame over a range of numbers.
I'm not great at loops so take a look if it helps:
k=1
for (i in 1:nrow(Data)){
for (l in 1: Data[i,2]){
for (j in 1: Data[i,5]){
Data[k,]<-Data[i,]
Data[k,3]<-Data[i,3]+j-1
k=k+1}
}
}
Here is a sample dataframe:
Data<- data.frame(matrix(NCOs = 4, nrow = 2))
x <- c("gid","did", "pid","plays")
colnames(Data) <- x
Data[1,]<-c(1,1,2,8)
Data[2,]<-c(1,2,12,6)
Output should have a total of 14 rows and looks like this
1 1 2 8
1 1 3 8
1 1 4 8
.
.
.
.
1 2 12 6
1 2 13 6
.
.
1 2 17 6
Upvotes: 0
Views: 71
Reputation: 388982
Maybe tidyr::complete
is a good choice here.
library(dplyr)
library(tidyr)
Data %>%
group_by(gid, did) %>%
complete(pid = seq(pid, pid + plays - 1)) %>%
fill(plays)
# gid did pid plays
# <dbl> <dbl> <dbl> <dbl>
# 1 1 1 2 8
# 2 1 1 3 8
# 3 1 1 4 8
# 4 1 1 5 8
# 5 1 1 6 8
# 6 1 1 7 8
# 7 1 1 8 8
# 8 1 1 9 8
# 9 1 2 12 6
#10 1 2 13 6
#11 1 2 14 6
#12 1 2 15 6
#13 1 2 16 6
#14 1 2 17 6
Upvotes: 3