How to split a R data frame into vectors (unbind)

后端 未结 2 2086
孤独总比滥情好
孤独总比滥情好 2021-01-06 04:43

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 th

相关标签:
2条回答
  • 2021-01-06 05:16

    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"
    
    0 讨论(0)
  • 2021-01-06 05:32

    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"
    
    0 讨论(0)
提交回复
热议问题