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?
You should be careful with the use of
assign, though. You can achieve almost the same result usingattach(mock), which is reversible (detach()) and won’t unintentionally overwrite existing variables (it just masks them).