R语言 如何使用异构子列表扁平化列表

pkln4tw6  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(134)

init_listlist_clustered_by_name开始,我想到达desired_list。我想知道是否有比我在这里开发的过程更好的过程:
也许是map_if之类的东西,检查长度,但我不能。

library(purrr)

cluster_by_name <- function (y) {
  map(unique(names(y)), ~ paste(unique(y[which(names(y)==.)]), collapse=", ")) %>% 
  setNames(unique(names(y)))
}

flatten_sublist <- function(x, colnames) {
  for (colname in colnames){
    x <- append(x, unlist(x[[colname]]))
    x[[colname]] <- NULL
  }
  x
}

vec <- c("A"=1,"B"=2, "A"=1, "B"=4)
vec2 <- c("A2"=1,"B2"=2, "A2"=3, "B2"=4)

init_list <- list(vec=vec, C=1, vec2=vec2)

init_list # starting point

list_clustered_by_name <- init_list %>% 
  map_if(function(x) length(x) > 1,
    function (y) cluster_by_name(y)
  )

list_clustered_by_name # possible starting point
# $vec
# $vec$A
# [1] "1"
# $vec$B
# [1] "2, 4"

# $C
# [1] 1

# $vec2
# $vec2$A2
# [1] "1, 3"
# $vec2$B2
# [1] "2, 4"

composed <- keep(list_clustered_by_name, ~(length(.) > 1), ~.)
single_features <- keep(list_clustered_by_name, ~(length(.) == 1), ~.)

composed_flattened <- flatten_sublist(composed, names(composed))

desired_list <- c(composed_flattened, single_features)

desired_list
# $A
# [1] "1"

# $B
# [1] "2, 4"

# $A2
# [1] "1, 3"

# $B2
# [1] "2, 4"

# $C
# [1] 1
x6h2sr28

x6h2sr281#

这可能对你有用:

library(purrr)

map_if(init_list, ~ length(.x) > 1, ~ as.list(tapply(.x, names(.x), \(y) toString(unique(y))))) |>
  list_flatten(name_spec = "{inner}")

$A
[1] "1"

$B
[1] "2, 4"

$C
[1] 1

$A2
[1] "1, 3"

$B2
[1] "2, 4"
wko9yo5t

wko9yo5t2#

我不确定我的方法比你的好,但这是我想到的

library(data.table)

# Helper functions
f1 <- \(v) data.table(s=names(v),k=v)[, paste0(unique(k),collapse=", "),s]
f2 <- \(d) unlist(apply(unname(as.matrix(d)),1, \(r) setNames(list(r[2]),r[1])),F)

# apply the helper functions to the elements of init_list that are named vectors
result = lapply(names(init_list), \(nv) {
  v = init_list[[nv]]
  if(!is.null(names(v))) f2(f1(v)) else setNames(list(v), nv)
})

# unlist the result
result = unlist(result, F)

输出:

$A
[1] "1"

$B
[1] "2, 4"

$C
[1] 1

$A2
[1] "1, 3"

$B2
[1] "2, 4"

相关问题