Pretty trivial task but couldn't find the answer and struggling with getting proper solution.
I want to combine lots of different variables(lists) containing unequal amount of string data into single data.frame object where first column gets the variable name and second it's assigned values.
E.g.
Variable_1
name
1 actor_id
2 first_name
3 last_name
4 last_update
Variable_2
name
1 address_id
2 address
3 address2
4 district
5 city_id
6 postal_code
7 phone
8 last_update
Expectd output:
1 Variable_1 actor_id
2 Variable_1 first_name
3 Variable_1 last_name
4 Variable_1 last_update
5 Variable_2 address_id
6 Variable_2 address
7 Variable_2 address2
8 Variable_2 district
9 Variable_2 city_id
10 Variable_2 postal_code
11 Variable_2 phone
12 Variable_2 last_update
i bet there must be multiple aproaches. thanks for the tips in advance!
CodePudding user response:
Assuming the list
object is named, create a new column from the names
and rbind
the list
elements with do.call
out <- do.call(rbind, Map(cbind, varname = names(lst1), lst1))
row.names(out) <- NULL
Or we may use bind_rows
library(purrr)
library(dplyr)
bind_rows(lst1, .id = 'varname') %>%
as_tibble
data
lst1 <- list(Variable_1 = structure(list(name = c("actor_id", "first_name",
"last_name", "last_update")), class = "data.frame", row.names = c("1",
"2", "3", "4")), Variable_2 = structure(list(name = c("address_id",
"address", "address2", "district", "city_id", "postal_code",
"phone", "last_update")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8")))
CodePudding user response:
Example data
variable1 <- paste0("variable1_",1:2)
variable2 <- paste0("variable2_",1:3)
How to
expand.grid(variable1,variable2)
Result
Var1 Var2
1 variable1_1 variable2_1
2 variable1_2 variable2_1
3 variable1_1 variable2_2
4 variable1_2 variable2_2
5 variable1_1 variable2_3
6 variable1_2 variable2_3