Search code examples
rlistloopsnames

Loop over list to assign names in R not working


I have a bunch of rows I'm adding to a larger dataframe called bigger_false. I want to do this using for loops. Each row looks like this:

new_row1 <- c(402, 1, "false alarm", 0)

I want to assign each of the new rows names of columns of the larger dataframe, so I'm looping over each row in a list and assigning the same names to each.

rowlist = list(new_row1, new_row2, new_row3, new_row4, new_row5, new_row6, new_row1011, new_row1014, new_row1016, new_row1022, new_row1023, new_row2021, new_row3046)

for (item in rowlist) {
      names(item) <- c("guest_id", "sessionNum", "interactions.hitType", "n")
    }

Then I'm looping over each and adding them to the big dataframe, which already has those column names.

for (item in rowlist) {
      bigger_false <- rbind(bigger_false, item)
    }

Now, the first loop seems to work for the first row (it successfully gets assigned the names). So if I manually do

bigger_false <- rbind(bigger_false, new_row1)

I get no error. However, the rest of that first loop does not successfully assign the rest of the rows the names, so the rbind loop gives the error: "Argument 2 must have names" after the first iteration.

Why is this happening? Thanks in advance.


Solution

  • The item variable loops over rowlist but doesn' modify the content of rowlist.
    Try:

    new_row1 <- c(402, 1, "false alarm", 0)
    new_row2 <- c(403, 2, "false alarm", 0)
    
    rowlist = list(new_row1, new_row2)
    
    for (item in 1:length(rowlist)) {
      names(rowlist[[item]]) <- c("guest_id", "sessionNum", "interactions.hitType", "n")
    }
    
    bigger_false <- NULL
    for (item in rowlist) {
      bigger_false <- rbind( item, bigger_false)
    }
    bigger_false
    
         guest_id sessionNum interactions.hitType n  
    item "403"    "2"        "false alarm"        "0"
    item "402"    "1"        "false alarm"        "0"