[英]Split dataframes within a list
我想知道如何拆分列表中包含的幾個數據幀。 我有一個包含200個數據框的列表,每個數據框包含兩列,即價格和數量。 我想將其拆分為一個價格為200 df的列表,另一個價格為200 df的列表。
謝謝
您正在尋找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在評論中說的那樣,為了完全回答這個問題,我應該使用'['
而不是'[['
。 后者返回向量 ,前者返回sub-data.frames 。 OP要求“一個價格為200 df的列表,另一個價格為200 df的列表”。
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
為此, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.