Use the following R Snippet to export a DataFrame column to a list in R:
your_R_list <- as.list(your_df$your_column)
Or using dplyr:
library(dplyr)
your_R_list <-your_df %>%
pull(your_column) %>%
as.list()
Write R column to a list – practical example
Create R DataFrame
We will first create a simple R DataFrame:
area <- c ('Python', 'Javascript', 'R', 'Go', 'Javascript', 'C#')
median_salary <- c (149, 112, 155, 144, 133, 122)
interviews <- data.frame (area = area,salary = median_salary)
Export R column to list with Dplyr Pull
When using the dplyr library, we have several ways to convert a column to a list.
The simplest is using the pull function which extracts a single column:
library(dplyr)
languages_lst <- interviews %>%
pull(area) %>%
as.list()
We can now print the list if needed and get the following list of characters:
[[1]] [1] "Python" [[2]] [1] "Javascript" [[3]] [1] "R" [[4]] [1] "Go" [[5]] [1] "Javascript" [[6]] [1] "C#"
Import Note: You need to ensure that either tidyverse or dplyr are installed in your system before using them.
Convert using Dplyr Select function
Another option is to use the dplyr select function which returns a DataFrame that has to be further slices to obtain our column:
library(dplyr)
languages_lst <- interviews %>%
select (area) %>%
.$area%>%
as.list()
Write a list with R base
We can use the basic R capability to obtain our list of characters:
salary_lst <- as.list(interviews$area)
Export DataFrame column as a vector
For completeness, we can also write the column to an R vector and then cast to a list:
salary_vector <- interviews$area
salary_lst <- as.list(salary_vector)