Set Data Frame Variables as List Items in R (Example Code)
In this R post you’ll learn how to set a data frame column as list element.
Introducing Example Data
data(iris) # Loading example data iris_small <- head(iris) # Reduce size of example data iris_small # Showing head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading example data iris_small <- head(iris) # Reduce size of example data iris_small # Showing head of example data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example: Set Data Frame Columns as List Elements
iris_list <- list() # Constructing empty list object for(i in 1:ncol(iris_small)) { # Convert variables to list elements iris_list[[i]] <- iris_small[ , i] } names(iris_list) <- colnames(iris_small) # Change names of list elements iris_list # Showing list in RStudio console # $Sepal.Length # [1] 5.1 4.9 4.7 4.6 5.0 5.4 # # $Sepal.Width # [1] 3.5 3.0 3.2 3.1 3.6 3.9 # # $Petal.Length # [1] 1.4 1.4 1.3 1.5 1.4 1.7 # # $Petal.Width # [1] 0.2 0.2 0.2 0.2 0.2 0.4 # # $Species # [1] setosa setosa setosa setosa setosa setosa # Levels: setosa versicolor virginica # |
iris_list <- list() # Constructing empty list object for(i in 1:ncol(iris_small)) { # Convert variables to list elements iris_list[[i]] <- iris_small[ , i] } names(iris_list) <- colnames(iris_small) # Change names of list elements iris_list # Showing list in RStudio console # $Sepal.Length # [1] 5.1 4.9 4.7 4.6 5.0 5.4 # # $Sepal.Width # [1] 3.5 3.0 3.2 3.1 3.6 3.9 # # $Petal.Length # [1] 1.4 1.4 1.3 1.5 1.4 1.7 # # $Petal.Width # [1] 0.2 0.2 0.2 0.2 0.2 0.4 # # $Species # [1] setosa setosa setosa setosa setosa setosa # Levels: setosa versicolor virginica #
Further Resources & Related Tutorials
Please find some additional R tutorials on topics such as data conversion, character strings, and factors in the following list.