I am having some trouble with a nested for loop. If I run the code without nesting the for loop, I get the outcome I want. I need it to happen within the nest though, but I currently get an error stating:
"Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 1"
Although, I don't get this when I run it outside of the for-loop. Do you have any advice on how I should proceed to get running as a nested loop?
Here is sample data
Route Year ID Amount
1 1 A 5
1 2 A 2
1 3 A 7
1 4 A 1
1 1 B 5
1 2 B 11
1 3 B 0
1 4 B 2
ID_list<- unique(data$ID)
for(i in 1:length(ID_list)){
ID <- data[which(data$ID== ID_list[i]), ]
route_list <- unique(ID$Route)
for(j in 1:length(route_list)){
SP_R <- ID[which(ID$Route == route_list[j]), ]
for(k in 1:(nrow(SP_R)-1)){
for(l in (k+1):nrow(SP_R)){
new_data<- rbind(new_data,cbind(SP_R[k,],SP_R[l,]))
}}}}
This gives me the error. I'm guessing it is because k and l are different lengths, but if I run the last part outside of the for loop (as a separate one - see below) it works.
for(i in 1:length(ID_list)){
ID <- data[which(data$ID== ID_list[i]), ]
route_list <- unique(ID$Route)
for(j in 1:length(route_list)){
SP_R <- ID[which(ID$Route == route_list[j]), ]
}}
for(k in 1:(nrow(SP_R)-1)){
for(l in (k+1):nrow(SP_R)){
new_data<- rbind(new_data,cbind(SP_R[k,],SP_R[l,]))
}}
I have no idea why this would be. Thank you for your advice!