简体   繁体   中英

Make vector of each column of a dataframe and return the vectors in a list

I have a dataframe like:

df<-data.frame(x=1:5,y=6:10,z=11:15)



 x  y  z
1 1  6 11
2 2  7 12
3 3  8 13
4 4  9 14
5 5 10 15

Now I would like to create a list new_list where every element is a single column of as a vector.

This would look like:

str(new_list)
list of 3
$ : num[1:5] 1 2 3 4 5
$ : num[1:5] 6 7 8 9 10
$ : num[1:5] 11 12 13 14 15

I tried:

new_list <-lapply(df,c)

but this only returend

list of 3
$ : num[1:5] 1
$ : num[1:5] 6
$ : num[1:5] 11

Note: I hope my goal is clear. If not plese let me know.

Using c .

l <- lapply(df, c)
str(l)
# List of 3
#  $ x: int [1:5] 1 2 3 4 5
#  $ y: int [1:5] 6 7 8 9 10
#  $ z: int [1:5] 11 12 13 14 15

or as.list .

l <- as.list(df)
str(l)
# List of 3
#  $ x: int [1:5] 1 2 3 4 5
#  $ y: int [1:5] 6 7 8 9 10
#  $ z: int [1:5] 11 12 13 14 15

Using identity()

lapply(df, identity)

Just modifying the attributes and class:

new_list <- unclass(df)
attr(new_list, "row.names") <- NULL

Or

new_list <- df
class(new_list) <- "list" # NULL also works but is not as clear
attr(new_list, "row.names") <- NULL

A data.frame is just a list with some additional attributes. The simplest way to turn a data.frame into a list with the structure you have requested is to remove all the attributes.

If you need to create a new object, you can copy the existing one and then strip it.

new_list <- df

attributes(new_list) <- NULL

> str(new_list)
List of 3
 $ : int [1:5] 1 2 3 4 5
 $ : int [1:5] 6 7 8 9 10
 $ : int [1:5] 11 12 13 14 15

However, this is usually done "in the wild" using as.list() , even though this retains variable names and has some additional overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM