0

I want to add additional rows to a dataframe using a loop. I have a list of API endpoints to cycle thru via a loop. Each iteration of the loop will deliver a single row of data. I can't get beyond how to get additional rows (i.e. i = 2 is row 2 of my df and so on) so that each iteration adds a row of data to the dashboard df. With what I've included below I'm getting a dashboard df that is 13 obs w/ 0 variables

dashboard <- data.frame()

for (i in 1:x){
  node <- fromJSON(acct_hotspots_api_ep[i])
  node <- as.data.frame(node)
  
other functions/commands.....

  rewards <- merge(rewards, last24h)
  rewards <- merge(rewards, last7)
  rewards <- merge(rewards, last30)
  rewards <- merge(rewards, last90)
dashboard[i,] <- rewards[1,]
}

  • `merge()` is for SQL-style joins, so I'm not sure that's what you want (which is probably `rbind()`. But [don't grow data frames (or anything in R)](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf); [make a list and combine them](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207), e.g. with [`purrr::map_dfr()`](https://purrr.tidyverse.org/reference/map.html). – alistaire May 17 '21 at 02:36
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah May 17 '21 at 04:07

1 Answers1

0

As alistaire suggests, you could implement rbind() inside the loop. Without your data it's hard to know the exact structure, but you could try something like this:

# setup your empty df (the 'container')
dashboard <- data.frame()

# setup the loop
for(i in 1:10){

  #~~~~~ step 1: generate your 'rewards' ~~~~~

    # sample 'rewards' data
    rewards <- i * 2

    # and/or your other functions...
    # rewards <- merge(rewards, last24h)
    # rewards <- merge(rewards, last7)
    # rewards <- merge(rewards, last30)
    # rewards <- merge(rewards, last90)

  #~~~~~ step 2: put the rewards into a df ~~~~~
    rewards_df <- data.frame(rewards = rewards,
                            i = i) # sometimes it's handy to include the value of i that got you the result (for troubleshooting or later analysis)

  #~~~~~ step 3: rbind the rewards df to your container ~~~~~
    dashboard <- rbind(dashboard, rewards_df)

}

# view your resulting df
dashboard

Dharman
  • 30,962
  • 25
  • 85
  • 135
hugh-allan
  • 1,170
  • 5
  • 16