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

StackOverflow https://stackoverflow.com/questions/16052239

  •  04-04-2022
  •  | 
  •  

Question

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?

Was it helpful?

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.

OTHER TIPS

while I agree with @RomanLustrik s comment that this is probably not a good idea, the function you are looking for is assign

for (i in colnames(x)) 
  assign(i, subset(x, select=i))

> A
#   A
# 1 1
# 2 2

> B
#   B
# 1 2
# 2 3

that being said, are you aware of the attach function?

 ?attach
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top