I have two types of data.
type_1 <- list(
"One" = "Something",
"Two" = "Something Else"
)
type_2 <- list(
"One" = c(1,2,3),
"Two" = c(4,5,6)
)
For both types I would like to create dataframes where the left hand side, or listnames (One & Two
) are column_one
, and where the right hand side are column_two
.
I tried a few of these approaches without much success.
What is the correct way to do this?
Desired output:
type_1 <- structure(
list(column__one = list("One","Two"), column_two = list("Something", "Something Else")),
row.names = c("A", "B"), class = "data.frame")
column__one column_two
A One Something
B Two Something Else
type_2 <- structure(
list(column__one = list("One","Two"), column_two = list(a= c(1,2,3), b=c(4,5,6))),
row.names = c("A", "B"), class = "data.frame")
column__one column_two
A One 1, 2, 3
B Two 4, 5, 6
CodePudding user response:
We can use enframe
from tibble
library(tibble)
library(tidyr)
enframe(type_1, name = "column_one", value = "column_two") %>%
unnest(column_two)
# A tibble: 2 × 2
column_one column_two
<chr> <chr>
1 One Something
2 Two Something Else
enframe(type_2, name = "column_one", value = "column_two")
# A tibble: 2 × 2
column_one column_two
<chr> <list>
1 One <dbl [3]>
2 Two <dbl [3]>
Or in base R
with stack
stack(type_1)[2:1]
ind values
1 One Something
2 Two Something Else
The second one will return a normal column as well
stack(type_2)[2:1]
ind values
1 One 1
2 One 2
3 One 3
4 Two 4
5 Two 5
6 Two 6
CodePudding user response:
A method with map_dfr()
from purrr
:
library(tidyverse)
map_dfr(type_1, ~ tibble(column_two = .x), .id = "column_one")
# # A tibble: 2 × 2
# column_one column_two
# <chr> <chr>
# 1 One Something
# 2 Two Something Else
map_dfr(type_2, ~ tibble(column_two = list(.x)), .id = "column_one")
# # A tibble: 2 × 2
# column_one column_two
# <chr> <list>
# 1 One <dbl [3]>
# 2 Two <dbl [3]>