Create data.frame from nested lapply’s
Last Updated :
11 Jul, 2023
In R, nested `lapply()` functions can be used to create a data frame from a nested list. This approach allows you to apply a function to each element of the nested list and then convert the processed data into a structured tabular format. This can be useful when dealing with complex data structures and you want to organize the data into a data frame for further analysis.
- `lapply()`: It is a function in R used to apply a specified function to each element of a list or vector and returns a list of the results.
- Nested lists: A nested list is a list that contains other lists as its elements, creating a hierarchical structure.
- Data frame: A data frame is a two-dimensional tabular data structure in R Programming Language, where columns can have different types (e.g., numeric, character, factor, etc.).
Create a data frame from a Nested List using lapply()
Creating a data frame from a nested list of numbers.
R
nested_list <- list (
list (1, 2, 3),
list (4, 5, 6),
list (7, 8, 9)
)
processed_list <- lapply (nested_list, function (x) {
lapply (x, function (y) {
y * 2
})
})
result <- as.data.frame ( matrix ( unlist (processed_list),
ncol = length (nested_list),
byrow = TRUE ))
result
|
Output:
V1 V2 V3
1 2 4 6
2 8 10 12
3 14 16 18
Creating a data frame from a Nested List of Strings
R
nested_list <- list (
list ( "apple" , "banana" , "cherry" ),
list ( "dog" , "cat" , "elephant" ),
list ( "red" , "blue" , "green" )
)
processed_list <- lapply (nested_list, function (x) {
lapply (x, function (y) {
paste0 (y, "_fruit" )
})
})
result <- as.data.frame ( matrix ( unlist (processed_list),
ncol = length (nested_list),
byrow = TRUE ))
result
|
Output:
V1 V2 V3
1 apple_fruit banana_fruit cherry_fruit
2 dog_fruit cat_fruit elephant_fruit
3 red_fruit blue_fruit green_fruit
Creating a data frame from a nested list with missing values.
R
nested_list <- list (
list (1, 2, NA ),
list (4, NA , 6),
list (7, 8, 9)
)
processed_list <- lapply (nested_list, function (x) {
lapply (x, function (y) {
ifelse ( is.na (y), 0, y)
})
})
result <- as.data.frame ( matrix ( unlist (processed_list),
ncol = length (nested_list),
byrow = TRUE ))
result
|
Output:
V1 V2 V3
1 1 2 0
2 4 0 6
3 7 8 9
The output is a data frame where each element of the nested list has been processed and transformed according to the applied function. The resulting data frame has the same dimensions as the nested list, with each element occupying a cell in the data frame.
Share your thoughts in the comments
Please Login to comment...