4

I'm relatively new to R and have been trying to find a solution to this problem for a while. I am trying to take a data frame and essentially do the reverse of rbind, so that I can split an entire data frame (and hopefully preserve the original data frame) into separate vectors, and use the row.names as the source of the new variable names.

So if I have a data.frame like this:

      Col1  Col2 Col3
Row1   A     B    C
Row2   D     E    F
Row3   G     H    I

I would like the end result to be separate vectors:

Row1 = A B C
Row2 = D E F
Row3 = G H I

I know I could subset specific rows out of the data.frame, but I want all of them separated. In terms of methodology could I use a for loop to move each row into a vector, but I wasn't exactly sure how to assign row names as variable names.

Jaap
  • 81,064
  • 34
  • 182
  • 193
goofnaggle
  • 43
  • 1
  • 3

2 Answers2

4

You can split the dataset by row after converting to matrix, set the names (setNames) of the list elements as 'Row1:Row3' and use list2env to assign the objects in the global environment.

 list2env(setNames(split(as.matrix(df),
        row(df)), paste0("Row",1:3)), envir=.GlobalEnv)

 Row1
 #[1] "A" "B" "C"
 Row2
 #[1] "D" "E" "F"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Note that there may be some type conversion depending on the classes of the fields in your data.frame – Jthorpe Jan 29 '15 at 18:20
  • @Jthorpe Yes, I understand, but here the OP wants to get the rows. There is always going to be a problem in that respect as we have only column classes. From the example, I assumed that it is all of the same class. One option might be to transpose, convert to data.frame, etc.... – akrun Jan 29 '15 at 18:22
1

A slightly different approach than @akrun's:

Df <- data.frame(matrix(LETTERS[1:9],nrow=3))
##
R> ls()
[1] "Df"
##
sapply(1:nrow(Df), function(x){
  assign(paste0("Row",row.names(Df)[x]),
         value=Reduce(function(x,y){c(x,y)},Df[x,]),
         envir=.GlobalEnv)
})
##
R> ls()
[1] "Df"   "Row1" "Row2" "Row3"
R> Row1
[1] "A" "D" "G"
R> Row2
[1] "B" "E" "H"
R> Row3
[1] "C" "F" "I"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
nrussell
  • 18,382
  • 4
  • 47
  • 60