Peter Bonate
Peter Bonate

Reputation: 85

Break apart a dataframe into individual named vectors

Is there an easy function, outside of attach/detach, that will break apart a dataframe or data table into its individual vectors with the names of the vectors as the names of the columns in the dataframe.

For example, suppose I have a data frame
x <- data.frame(a=c(1,2,3), b=c(4,5,6), d=c(7,8,9))

Then using the function it would return 3 vectors: a, b, and d. Seems like there should be function to do this but I cannot find it.

Upvotes: 0

Views: 92

Answers (3)

mhovd
mhovd

Reputation: 4087

While two answers have already been posted, I would like to suggest a solution that does not write to the global environment, which is generally considered to be a bad thing (see Dirk´s comments on attach).

First of all, R can only return single objects. It is not possible to return three, separate vectors. However, we can easily return a list of vectors.

df <- data.frame(a=c(1,2,3), b=c(4,5,6), d=c(7,8,9))

# Returns a named list
as.list(df)
#> $a
#> [1] 1 2 3
#> 
#> $b
#> [1] 4 5 6
#> 
#> $d
#> [1] 7 8 9

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368599

Yes, there is a (very old, very standard) function called attach() that does that:

> x <- data.frame(a=c(1,2,3), b=c(4,5,6), d=c(7,8,9))
> attach(x)
> a
[1] 1 2 3
> b
[1] 4 5 6
> d
[1] 7 8 9
>

However, the general consensus is to Don't Do That (TM) as it can a) clutter the environment into which you attach() (usually the global one) and can b) silently overwrite an existing variable (though it warns by default unless you override a switch, see ?attach). There is a counterpart detach() to remove them too. The (aptly named) Section "Good Practice" in the help page for attach has more on all this, including a hint to use on.exit() with detach() where you use attach().

But if you need it, you can use it. Just be aware of Them Dragons.

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

One option would be list2env

list2env(x,.GlobalEnv)

a
#[1] 1 2 3
b
#[1] 4 5 6
d
#[1] 7 8 9

Upvotes: 3

Related Questions