pillai
April 3, 2019, 10:32am
1
hi R's
Please someone help me in this situation,
your_list <- list(
PERSON1 = list(
group = "A,B,C",
name = "PersonName1",
age = 25
),
PERSON2 = list(
group = "X,Y,Z",
name = "PersonName2",
age = 28
)
)
i would like to unwind the rows based on the column Group
the expected Result is as below
ID | name | group | age
PERSON1 | PersonName1 | A | 25
PERSON1 | PersonName1 | B | 25
PERSON1 | PersonName1 | C | 25
PERSON2 | PersonName2 | X | 28
PERSON2 | PersonName2 | Y | 28
PERSON2 | PersonName2 | Z | 28
Thanks in Advance
mara
April 3, 2019, 12:59pm
2
I'm sure there are other ways to do it, but you could use a combination of purrr::map()
and tidyr::separate_rows()
.
library(tidyverse)
your_list <- list(
PERSON1 = list(
group = "A,B,C",
name = "PersonName1",
age = 25
),
PERSON2 = list(
group = "X,Y,Z",
name = "PersonName2",
age = 28
)
)
df <- tibble(
"id" = names(your_list),
"name" = map_chr(your_list, "name"),
"group" = map(your_list, "group"),
"age" = map_dbl(your_list, "age")
)
df %>%
separate_rows(group)
#> # A tibble: 6 x 4
#> id name group age
#> <chr> <chr> <chr> <dbl>
#> 1 PERSON1 PersonName1 A 25
#> 2 PERSON1 PersonName1 B 25
#> 3 PERSON1 PersonName1 C 25
#> 4 PERSON2 PersonName2 X 28
#> 5 PERSON2 PersonName2 Y 28
#> 6 PERSON2 PersonName2 Z 28
Created on 2019-04-03 by the reprex package (v0.2.1)
1 Like
Basically, it's the same solution which Mara did, but a little bit more concise:
library(magrittr)
your_list <- list(PERSON1 = list(group = "A,B,C",
name = "PersonName1",
age = 25),
PERSON2 = list(group = "X,Y,Z",
name = "PersonName2",
age = 28))
your_list %>%
do.call(rbind,.) %>%
as.data.frame() %>%
tibble::rownames_to_column() %>%
tidyr::separate_rows(group)
#> rowname group name age
#> 1 PERSON1 A PersonName1 25
#> 2 PERSON1 B PersonName1 25
#> 3 PERSON1 C PersonName1 25
#> 4 PERSON2 X PersonName2 28
#> 5 PERSON2 Y PersonName2 28
#> 6 PERSON2 Z PersonName2 28
Created on 2019-04-03 by the reprex package (v0.2.1)
2 Likes
pillai
April 3, 2019, 2:47pm
4
@mara @Yarnabrina
Wonderful guys, Thanks for your quick support..
1 Like
system
Closed
April 10, 2019, 3:04pm
6
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.