How do I Convert Data Frame Column to List in R

In R, you can convert a data frame column to a list by using the as.list() function. This function takes the data frame column as its argument and returns a list with the same values as the data frame column. You can then use the list for further manipulation or analysis.


You can use the following methods to convert a data frame column to a list in R:

Method 1: Convert One Column to List

my_list <- list(df$my_column)

Method 2: Convert All Columns to Lists

all_lists <- as.list(df)

The following examples show how to use each method in practice with the following data frame in R:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

Example 1: Convert One Data Frame Column to List in R

We can use the following code to convert the points column in the data frame to a list:

#convert points column to list
points_list <- list(df$points)

#view list
points_list

[[1]]
[1] 99 90 86 88 95

The new variable called points_list represents the points column in the data frame as a list.

We can use the class() function to confirm that points_list is indeed a list:

#display class of points_list
class(points_list)

[1] "list"

Example 2: Convert All Data Frame Columns to Lists in R

We can use the following code to convert each column in the data frame to a list:

#convert all columns to lists
all_columns_list <- as.list(df)

#view lists
all_columns_list 

$team
[1] "A" "B" "C" "D" "E"

$points
[1] 99 90 86 88 95

$assists
[1] 33 28 31 39 34

$rebounds
[1] 30 28 24 24 28

We can also use brackets [ ] to extract a specific column as a list:

#view first column as list
all_columns_list[1]

$team
[1] "A" "B" "C" "D" "E"

The output displays the first column in the data frame (“team”) as a list.


The following tutorials explain how to perform other common tasks in R:

x