Reputation: 330
I have a list, List_A
, which contains elements with a similar pattern. I am trying to nest the similar items based on the pattern. Example below
List_A <- list("Q_2020", "Q_2021", "C_2019", "C_2020", "K_2020")
Output:
# List of 5
# $ : chr "Q_2020"
# $ : chr "Q_2021"
# $ : chr "C_2019"
# $ : chr "C_2020"
# $ : chr "K_2020"
Desired Output:
# List of 3
# $ Q:List of 2
# ..$ : chr "Q_2020"
# ..$ : chr "Q_2021"
# $ C:List of 2
# ..$ : chr "C_2019"
# ..$ : chr "C_2020"
# $ K: chr "K_2020"
I know the pattern would be before "_"
so I am using sub()
to get the pattern - but I would like some input on how I can create the nested lists. My attempt is a bit too noisy: 1) extract pattern i.e. Q, K, C, 2) create nested list skeleton, 3) Loop an if statement.
Any input is appreciated.
Upvotes: 1
Views: 356
Reputation: 102890
Do you need this?
> str(split(List_A, factor(u <- substr(unlist(List_A), 1, 1), levels = unique(u))))
List of 3
$ Q:List of 2
..$ : chr "Q_2020"
..$ : chr "Q_2021"
$ C:List of 2
..$ : chr "C_2019"
..$ : chr "C_2020"
$ K:List of 1
..$ : chr "K_2020"
Upvotes: 1
Reputation: 887951
We could split by substring
v1 <- unlist(List_A)
subv1 <- trimws(v1, whitespace = "_.*")
List_A_new <- lapply(split(v1, factor(subv1, levels = unique(subv1))), as.list)
-output structure
str(List_A_new)
List of 3
$ Q:List of 2
..$ : chr "Q_2020"
..$ : chr "Q_2021"
$ C:List of 2
..$ : chr "C_2019"
..$ : chr "C_2020"
$ K:List of 1
..$ : chr "K_2020"
Upvotes: 1