Reputation: 2885
I have a data frame with many columns, named foo
, bar
, etc.
I would like to extract each column of the data frame to separate objects called foo
, bar
and so on. Is there an automated way to do this in R?
Working example:
mock <- structure(list(
x = structure(1:3, .Label = c("1", "2", "3"), class = "factor"),
y = structure(1:3, .Label = c("A", "B", "C"), class = "factor"),
z = structure(c(1L, 1L, 2L), .Label = c("0", "1"), class = "factor")),
.Names = c("x", "y", "z"), row.names = c(NA, -3L), class = "data.frame")
Output:
> mock
x y z
1 1 A 0
2 2 B 0
3 3 C 1
How can I write a loop that creates objects x
, y
and z
from the three columns of this data frame?
Upvotes: 2
Views: 280
Reputation: 3866
> for (i in 1:ncol(mock)) {
+ assign(names(mock)[i],mock[,i])
+ }
> x
[1] 1 2 3
Levels: 1 2 3
> y
[1] A B C
Levels: A B C
> z
[1] 0 0 1
Levels: 0 1
You should be careful with the use of assign
, though. You can achieve almost the same result using attach(mock)
, which is reversible (detach()
) and won't unintentionally overwrite existing variables (it just masks them).
Upvotes: 2