Search code examples
rdataframerowsstoring-data

Saving rows into variables in R


I have a 18-by-48 matrix. Is there a way to save each of the 18 rows automatically in a separate variable (e.g., from r1 to r18) ?


Solution

  • I'd definitely advise against splitting a data.frame or matrix into its constituent rows. If i absolutely had to split the rows up, I'd put them in a list then operate from there.

    If you desperately had to split it up, you could do something like this:

    toy <- matrix(1:(18*48),18,48)
    
    variables <- list()
    for(i in 1:nrow(toy)){
      variables[[paste0("variable", i)]] <- toy[i,]
    }
    
    list2env(variables, envir = .GlobalEnv)
    

    I'd be inclined to stop after the for loop and avoid the list2env. But I think this should give you your result.