'Storing looping rows in R
laststop <- NULL
stopinfo <- NULL
for (i in journeys$JourneyID){
laststop <- get_last_stop(i)
stopinfo <- c(stop_info(i,laststop))
final_stops <- data.frame(stopinfo)
}
Basically, through stop_info function with two variables laststop and I, I can get a output 1 row with 8colums. I can get only one row with this data.freme code above. What I want to get is a complete dataframe named final_stops. when I type rint(final_stops), I can see the whole 300 outcomes I need.
But I don't know how to make it into the complete dataframe
Solution 1:[1]
Difficult to tell if you do not show a minimum reproducible example. But, assuming you get every iteration a data.frame of one row, same columns and you would like to have all of them together, you could use rbind():
laststop <- NULL
stopinfo <- NULL
for (i in journeys$JourneyID){
laststop <- get_last_stop(i)
stopinfo <- c(stop_info(i,laststop))
if (i==1){ # If it is the first iteration: creates the variable
final_stops <- data.frame(stopinfo)
} # if it is second or later iteration, bind by row
else {
final_stops <- rbind(final_stops , data.frame(stopinfo)) # combine rows
}
}
However, this is probably not the best solution and likely you could apply your functions in a tidyverse/data.frame operations much cleaner way. But with custom functions and not a data example, impossible to say.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RobertoT |
