在列表中拆分数据框

Split dataframes within a list

我想知道如何拆分列表中包含的多个数据框。 我有一个包含 200 个数据框的列表,每个数据框包含两列,价格和数量。我想拆分它,并有一个包含 200 df 价格的列表和另一个包含 200 df 体积的列表。

谢谢

purrr 有一个巧妙的功能就是为了这个

数据

set.seed(1)
your_list <- list(data.frame(Price = sample(10,2),Volume = sample(10,2)),
     data.frame(Price = sample(10,2),Volume = sample(10,2)),
     data.frame(Price = sample(10,2),Volume = sample(10,2)))
# [[1]]
#   Price Volume
# 1     3      6
# 2     4      9
# 
# [[2]]
#   Price Volume
# 1     3     10
# 2     9      6
# 
# [[3]]
#   Price Volume
# 1     7      3
# 2     1      2

结果

library(purrr)
map(your_list,"Price")
# [[1]]
# [1] 3 4
# 
# [[2]]
# [1] 3 9
# 
# [[3]]
# [1] 7 1

map(your_list,"Volume")
# [[1]]
# [1] 6 9
# 
# [[2]]
# [1] 10  6
# 
# [[3]]
# [1] 3 2

您正在寻找 purrr::transpose

set.seed(1)
your_list <- list(data.frame(Price = sample(10,2),Volume = sample(10,2)),
                  data.frame(Price = sample(10,2),Volume = sample(10,2)),
                  data.frame(Price = sample(10,2),Volume = sample(10,2)))
str(your_list)
#> List of 3
#>  $ :'data.frame':    2 obs. of  2 variables:
#>   ..$ Price : int [1:2] 3 4
#>   ..$ Volume: int [1:2] 6 9
#>  $ :'data.frame':    2 obs. of  2 variables:
#>   ..$ Price : int [1:2] 3 9
#>   ..$ Volume: int [1:2] 10 6
#>  $ :'data.frame':    2 obs. of  2 variables:
#>   ..$ Price : int [1:2] 7 1
#>   ..$ Volume: int [1:2] 3 2
str(purrr::transpose(your_list))
#> List of 2
#>  $ Price :List of 3
#>   ..$ : int [1:2] 3 4
#>   ..$ : int [1:2] 3 9
#>   ..$ : int [1:2] 7 1
#>  $ Volume:List of 3
#>   ..$ : int [1:2] 6 9
#>   ..$ : int [1:2] 10 6
#>   ..$ : int [1:2] 3 2

另一种方式,仅使用 base R。用 Moody_Mudskipper.

答案中的数据集进行测试
lapply(your_list, '[[', "Price")
lapply(your_list, '[[', "Volume")

编辑。
正如 Moody_Mudskipper 在他的评论中所说,为了完全回答我应该使用 '[' 而不是 '[[' 的问题。后者returnsvectors,前者returnssub-data.frames。并且 OP 要求 "one list with 200 df of Price and another list with 200 df of Volume".

lapply(your_list, '[', "Price")
#[[1]]
#  Price
#1     3
#2     4
#
#[[2]]
#  Price
#1     3
#2     9
#
#[[3]]
#  Price
#1     7
#2     1
lapply(your_list, '[', "Volume")
# output ommited