R语言 把tibbles列表变成向量列表

kd3sttzy  于 2023-06-19  发布在  其他
关注(0)|答案(5)|浏览(230)

如何将一个tibles列表(只有一个col)变成一个向量列表?列表对象的名称应该保持不变,并且应该省略tibble的col_name。感谢您的帮助,亲爱的高贵的程序员!

示例

a_tibble <- tibble(id = c('AB', 'DRR', 'FH', 'yyb'))
another_tibble <- tibble(id = c('AB', 'DXF', 'FH', 'DKH'))

list <- list(
  list1 = a_tibble,
  list2 = another_tibble,
  list3 = a_tibble,
  list4 = another_tibble)

预期结果

result <- list(
  list1 = (c('AB', 'DRR', 'FH', 'yyb')),
  list2 = (c('AB', 'DXF', 'FH', 'DKH')),
  list3 = (c('AB', 'DRR', 'FH', 'yyb')),
  list4 = (c('AB', 'DXF', 'FH', 'DKH'))
)
vngu2lb8

vngu2lb81#

您可以unlist每个list-

lapply(list, unlist, use.names = FALSE)

#$list1
#[1] "AB"  "DRR" "FH"  "yyb"

#$list2
#[1] "AB"  "DXF" "FH"  "DKH"

#$list3
#[1] "AB"  "DRR" "FH"  "yyb"

#$list4
#[1] "AB"  "DXF" "FH"  "DKH"
li9yvcax

li9yvcax2#

向量化的答案是:

unlist(list, recursive = FALSE)

# $list1.id
# [1] "AB"  "DRR" "FH"  "yyb"
# 
# $list2.id
# [1] "AB"  "DXF" "FH"  "DKH"
# 
# $list3.id
# [1] "AB"  "DRR" "FH"  "yyb"
# 
# $list4.id
# [1] "AB"  "DXF" "FH"  "DKH"

要删除.id,您可以执行以下操作:

gsub(".id", "", names(new_list), fixed = TRUE)

微基准测试:

library(microbenchmark)
mb <- microbenchmark(
  "lapply-unlist" = lapply(list, unlist, use.names = FALSE),
  "lapply-t" = lapply(list, \(i) c(t(i))),
  "unlist-rec" = unlist(list, recursive = FALSE),
  "lapply-pull" = lapply(list, dplyr::pull),
  "lapply-[[" = lapply(list, "[[", 1)
)

# Unit: microseconds
#           expr    min      lq     mean  median      uq    max neval
#  lapply-unlist   12.8   18.85   27.027   25.35   32.45  114.1   100
#       lapply-t  334.9  381.45  566.098  489.30  564.85 4213.3   100
#     unlist-rec    3.2    6.60   11.440   11.20   14.95   29.4   100
#    lapply-pull 1894.1 2170.80 2772.973 2580.15 3233.10 4976.2   100
#      lapply-[[   36.3   49.50   69.882   64.60   84.55  202.3   100
gab6jxml

gab6jxml3#

您可以转置和连接,即。

lapply(list, \(i)c(t(i)))
# or lapply(list, unlist) if you don't mind named vectors

$list1
[1] "AB"  "DRR" "FH"  "yyb"

$list2
[1] "AB"  "DXF" "FH"  "DKH"

$list3
[1] "AB"  "DRR" "FH"  "yyb"

$list4
[1] "AB"  "DXF" "FH"  "DKH"
70gysomp

70gysomp4#

使用pull

lapply(list, dplyr::pull)

$list1
[1] "AB"  "DRR" "FH"  "yyb"

$list2
[1] "AB"  "DXF" "FH"  "DKH"

$list3
[1] "AB"  "DRR" "FH"  "yyb"

$list4
[1] "AB"  "DXF" "FH"  "DKH"
9lowa7mx

9lowa7mx5#

lapply(list, "[[", 1)
# $list1
# [1] "AB"  "DRR" "FH"  "yyb"
# 
# $list2
# [1] "AB"  "DXF" "FH"  "DKH"
# 
# $list3
# [1] "AB"  "DRR" "FH"  "yyb"
# 
# $list4
# [1] "AB"  "DXF" "FH"  "DKH"

相关问题