当我有不同长度的列表时,如何获得 list_rbind() names_to 的好处?

问题描述 投票:0回答:1

我有两个从 JSON 下载中获得的大对象。在原始形式中,顺序很重要。 长度(种类)与长度(颜色)相同。我很高兴添加另一列或使用行名称。从 list_rbind() 来看,rows_to 是完美的,但是......

  • list_rbind() 不起作用,因为颜色不是 dfs 列表。
  • as.data.frame() 不起作用,因为颜色具有不同长度的列表
  • unlist() 丢失信息
    species <- c("roses", "tulips", "lilies")
    colors <- list(list("red"), list("white", "yellow"), list("pink", "white"))

想要的结果

      species colors
    1   roses    red
    2  tulips  white
    3  tulips yellow
    4  lilies   pink
    5  lilies  white

我可以使用 for 循环暴力破解所需的结果,但我有一百万种,每种至少有一种颜色,平均有八种。因此需要一种更智能、更快速的方法。不,现实世界的数据不是字符串。我需要更聪明的方法。

将不同长度的列表嵌套到数据帧似乎无法解决我的挑战。

现实世界

> str(pg, max.level = 2)
'data.frame':   1206169 obs. of  3 variables:
 $ PG : int  1 2 3 4 5 6 7 8 9 10 ...
 $ npi:List of 1206169
  ..$ : int  1376032029 1184159188 1629504501 1598703019 1487200408 1801443619
  ..$ : int 1588809248
  ..$ : int 1497791297
r list nested-lists
1个回答
0
投票

基础R

data.frame(
  species = rep(species, times = lengths(colors)),
  colors = unlist(colors)
)
#   species colors
# 1   roses    red
# 2  tulips  white
# 3  tulips yellow
# 4  lilies   pink
# 5  lilies  white
© www.soinside.com 2019 - 2024. All rights reserved.