Converting
Data Structures in R
Learn to seamlessly convert between vectors, lists, and data frames: the three foundational building blocks of R programming.
What Are Data Structures?
Data structures are containers that organize and store your data in R. Each structure has its own rules about what kind of data it can hold and how you can access it. The three most important ones for beginners are:
The Big Picture: How They Relate
Why Convert Between Structures?
Different R functions expect different input types. If your data is in the wrong container, you will get errors or unexpected results. Converting lets you:
The Core Conversion Functions
The Golden Rule of Conversion
Vector vs List: Key Differences
| Vector | List | |
|---|---|---|
| Data types | Homogeneous (one type) | Heterogeneous (mixed) |
| Access element | x[1] | x[[1]] or x$name |
| Nesting | Not possible | Lists inside lists |
| Created with | c() | list() |
| Convert to other | as.list() | unlist() |
How to Choose a Conversion
Example 1: Vector → List
Example 2: List → Vector
Example 3: Vectors → Data Frame
Example 4: Data Frame → Vector & List
Example 5: Named List → Data Frame
Common Mistakes to Avoid
Complete Conversion Reference
| From → To | Function | Watch For |
|---|---|---|
| Vector → List | as.list(x) | Each element becomes a list item |
| List → Vector | unlist(x) | Type coercion with mixed types |
| Vectors → Data Frame | data.frame(a, b) | Vectors must be equal length |
| List → Data Frame | as.data.frame(x) | List elements must be equal length |
| Data Frame → List | as.list(df) | Returns named list of column vectors |
| Data Frame → Vector | df$col | Extracts one column only |
Question 1 of 5
What does unlist(list(10, 20, 30)) return?
Question 2 of 5
What happens when you run unlist(list(1, "hello", TRUE))?
Question 3 of 5
Which function converts a data frame into a list of its columns?
Question 4 of 5
You have two vectors: x <- c("A", "B") and y <- c(1, 2, 3). What happens with data.frame(x, y)?
Question 5 of 5
Given my_list <- list(a = 1:3, b = 4:6), what is the class of as.data.frame(my_list)$a?