【问题标题】:data.table with unique names from nested list with different classes and missing namesdata.table 具有来自嵌套列表的唯一名称,具有不同的类和缺少名称
【发布时间】:2021-11-26 10:50:06
【问题描述】:

我有一个这种结构的嵌套列表:

test_list <- list(
  "some string",
  list(type = "entry_type", text = "some content"),
  list("more strings"),
  list(type = "another_type", text = "more text yet"),
  ""
)

所以它是一个包含列表和普通条目的列表,而唯一的名称是嵌套列表中的项目的名称——它们是重复的。

我的目标是将其转移到具有原始名称(假设它们存在)但唯一的 data.table 中。

目前我使用这个管道:

library(data.table)

dt <- as.data.table(flatten(test_list))

unique_names <- paste0("V", seq_len(length(names(dt))))
propper_names <- names(dt)

new_names <- propper_names

blank_names <- which(new_names == "")
new_names[blank_names] <- unique_names[blank_names]

duplicates_names <- which(duplicated(new_names))
new_names[duplicates_names] <- paste(
  propper_names[duplicates_names],
  unique_names[duplicates_names],
  sep = "_"
  )

setnames(
  dt,
  new_names
)

有没有更好/更快/更好/更健壮的方法来实现这个目标?

【问题讨论】:

  • flatten() 来自哪里?

标签: r data.table


【解决方案1】:

您可以使用 unlist rapply() 来保留嵌套更深的名称:

setDT(as.list(rapply(test_list, identity)))[]
setnames(DT, make.names(names(DT), unique = TRUE))
DT
#             V1       type         text           V2       type.1        text.1 V3
# 1: some string entry_type some content more strings another_type more text yet  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    相关资源
    最近更新 更多