我在2列(Region和GroupedCateg)中有数据。请参考下面的数据框。我想将其转换为嵌套列表。我尝试使用dplyr的group_by和do()函数,然后转换为list,但没有用。
df <- read.table(header = T,
text = '
Region GroupedCateg
Beja Alentejo
Evora Alentejo
Portalegre Alentejo
Faro Algarve
Aveiro Central
"Castelo Branco" Central
Coimbra Central
Leiria Central
Santarem Central
Acores Islands
Madeira Islands
Lisboa Lisbon
Setubal Lisbon
Braga North
Braganca North
"Viana do Castelo" North
"Vila Real" North
Porto Porto
')
列表中的所需输出。区域名称中。嵌套列表中的相应GroupedCateg
list(
list(
name = "Alentejo",
categories = list("Beja", "Evora", "Portalegre")
),
list(
name = "Algarve",
categories = list("Faro")
),
list(
name = "Central",
categories = list("Aveiro", "Castelo Branco", "Coimbra", "Leiria", "Santarem" )
),
list(
name = "North",
categories = list("Braga", "Braganca", "Viana do Castelo", "Vila Real")
),
list(
name = "Lisbon",
categories = list("Lisboa", "Setubal")
),
list(
name = "Islands",
categories = list("Acores", "Madeira")
),
list(
name = "Porto",
categories = list("Porto")
)
)
您可以pmap()
在中使用purrr
。
library(dplyr)
library(purrr)
x <- df %>%
group_by(GroupedCateg) %>%
summarise(Region = list(Region)) %>%
pmap(~ list(name = .x, categories = as.list(.y)))
对应的base
R版本:
y <- apply(aggregate(Region ~ GroupedCateg, df, c),
1, function(y) list(name = y[[1]], categories = as.list(y[[2]])))
all.equal(x, y)
# [1] TRUE
输出量
[[1]]
[[1]]$name
[1] "Alentejo"
[[1]]$categories
[[1]]$categories[[1]]
[1] "Beja"
[[1]]$categories[[2]]
[1] "Evora"
[[1]]$categories[[3]]
[1] "Portalegre"
[[2]]
[[2]]$name
[1] "Algarve"
[[2]]$categories
[[2]]$categories[[1]]
[1] "Faro"
[[3]]
[[3]]$name
[1] "Central"
[[3]]$categories
[[3]]$categories[[1]]
[1] "Aveiro"
[[3]]$categories[[2]]
[1] "Castelo Branco"
[[3]]$categories[[3]]
[1] "Coimbra"
[[3]]$categories[[4]]
[1] "Leiria"
[[3]]$categories[[5]]
[1] "Santarem"
[[4]]
[[4]]$name
[1] "Islands"
[[4]]$categories
[[4]]$categories[[1]]
[1] "Acores"
[[4]]$categories[[2]]
[1] "Madeira"
[[5]]
[[5]]$name
[1] "Lisbon"
[[5]]$categories
[[5]]$categories[[1]]
[1] "Lisboa"
[[5]]$categories[[2]]
[1] "Setubal"
[[6]]
[[6]]$name
[1] "North"
[[6]]$categories
[[6]]$categories[[1]]
[1] "Braga"
[[6]]$categories[[2]]
[1] "Braganca"
[[6]]$categories[[3]]
[1] "Viana do Castelo"
[[6]]$categories[[4]]
[1] "Vila Real"
[[7]]
[[7]]$name
[1] "Porto"
[[7]]$categories
[[7]]$categories[[1]]
[1] "Porto"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句