Search code examples
rdataframecol

Split a data.frame by columns and storing each column as an object with the column names as name of the object


HI this is a fundamental question that I have with R. I know there might be solutions out there to do my task, but I would like to ask why could my function wont work.

I have a data.frame that looks like this

A B C
1 2 3
2 3 4

and I want to store each of values in A, B or C into individual objects with names A, B and C.

So here my function

splitcolnames<-function(x)
  {for (i in colnames(x)){
    subset(x, select=c(i))->i}}
}

But it doesn't work. Can someone be kind and point out what did I not get right?


Solution

  • One of the following should do it for you, assuming your data.frame is named "mydf".

    lapply(names(mydf), function(x) assign(x, mydf[x], envir = .GlobalEnv))
    lapply(names(mydf), function(x) assign(x, mydf[, x], envir = .GlobalEnv))
    

    The first will create single-column data.frames, and the second will create vectors.

    Example in a clean session:

    > rm(list = ls())
    > ls()
    character(0)
    > mydf <- data.frame(A = c(1, 2), B = c(3, 4))
    > mydf
      A B
    1 1 3
    2 2 4
    > invisible(lapply(names(mydf), function(x) assign(x, mydf[x], envir = .GlobalEnv)))
    > ls()
    [1] "A"    "B"    "mydf"
    > A
      A
    1 1
    2 2
    > rm(list = ls())
    > mydf <- data.frame(A = c(1, 2), B = c(3, 4))
    > invisible(lapply(names(mydf), function(x) assign(x, mydf[, x], envir = .GlobalEnv)))
    > ls()
    [1] "A"    "B"    "mydf"
    > B
    [1] 3 4
    

    In the examples above in invisible to suppress the output.