【问题标题】:Nested list in R to stringR中的嵌套列表到字符串
【发布时间】:2019-01-09 21:49:35
【问题描述】:

如何将填充了嵌套列表的数据框列转换为文本字符串,但保留列表元素名称?

我试过了:

data_frame$column_new <- paste(unlist(data_frame$column), collapse = “”)

它可以工作,但会为相应行中的每个列表创建一个不保留列表元素名称的字符串,它几乎就在那里。

列表如下:

data_frame10000 obs. of 1 variable

column: list of 10000
..$ :list of 1
.. ..$ list of 6
.. .. ..$ apple : chr "small"
.. .. ..$ pear  : int 3
.. .. ..$ orange: list()
.. .. ..$ grape: list of 2

下一行 ..$ : 列表 1 .. ..$ 清单 6 .. .. ..$ apple : chr "small" .. .. ..$ 梨:int 3 .. .. ..$ 橙色:list() .. .. ..$ 葡萄:2 个列表

我希望将结果放回数据框单元格:

所以目前看起来是这样的:

data_frame$column
list
list
“”

到....

data_frame$column  new_column_string
list               new text string of every thing in list (with names kept)
list               new text string of list “”

他现在差不多了,

    <- sapply(data_frame$colum_string, 
                 function(x) paste(unlist(x, use.names = TRUE), collapse = “ “))

但不保留列表元素名称!!

【问题讨论】:

  • 您能否举一个具有预期输出的命名嵌套列表的示例?
  • 也许没有paste。这将保留名称:column &lt;- list(list(apple = 1L, pear = 3L)); unlist(column)
  • 问题是我不知道列表里面的名字是什么,能不知道就转成字符串吗?
  • 请以易于粘贴的方式提供您的数据,例如使用dput

标签: r list tidyverse purrr


【解决方案1】:
data_frame <- data.frame(column = I(list(
  list(list(apple = "large", pear = "small")), 
  list(banana = "tiny"), 
  list(list(kiwi = "fat", list(orange = "huge")))
)))

data_frame$new_column_string <- 
  vapply(data_frame$column, function(.x) {
    y <- unlist(.x, use.names = TRUE)
    paste(names(y), y, sep = ' = ', collapse = ', ')
  }, FUN.VALUE = character(1))
data_frame

#         column           new_column_string
# 1 list(app.... apple = large, pear = small
# 2         tiny               banana = tiny
# 3 list(kiw....   kiwi = fat, orange = huge

【讨论】:

  • 认为有混淆,我的意思是一个全文字符串,例如'apple ='1 next row'pear = 3'不是数字
  • 所以新列将包含“apple = 1”,有时这也可能是一个字符,例如“pear = new”
  • 如果数据帧是 data_frame
  • “mutate_impl(.data, dots) 中的错误:评估错误:列名必须是一维原子向量或列表” - 我认为这可能是因为有些行为空。有些列表元素为空,它可以处理/拉出空的列表名称吗? / 行为空?
  • 也不需要 ID,例如 apple = "large", pear = "small 将在单个字符串中,new_column_string = apple = large, pear = small" 在一行中
猜你喜欢
  • 2016-02-08
  • 2021-11-12
  • 2021-10-18
  • 2017-04-15
  • 2021-11-25
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多