簡體   English   中英

在 r 中創建嵌套列表

[英]create nested lists in r

我有一個數據框,我想用它進行回歸分析。 數據如下所示:

COMPANY <- c(rep("COMPANY_1",24),rep("COMPANY_2",24),rep("COMPANY_3",24))
YEAR <- rep(rep(2014:2019, each = 4),3)
SEASON <- rep(c("SPRING","SUMMER","AUTUMN","WINTER"),18)
X <- sample(100:1000,72)
Y <- sample(10:100,72)
df_ALL <- data.frame(COMPANY, YEAR, SEASON, X, Y)

但是,我不想僅基於此數據集進行分析,還想基於各種子集(例如:僅公司 1、僅適用於冬季、僅適用於冬季的公司 1 等)。 我成功地做到了這一點,方法是創建一個嵌套列表,然后使用 lapply 對嵌套列表中的每個數據框執行回歸 (plm)。 回歸結果然后存儲在第二個嵌套列表中,我可以從那里輕松訪問它們。

但是,我創建嵌套列表的過程對我來說似乎非常不專業且容易出錯。 這是我用於創建嵌套列表的代碼:

nested_list <- vector(mode="list", length=2)
nested_list <- setNames(nested_list, c("2014-2016","2017-2019"))
for (i in 1:2) {
  nested_list[[i]] <- vector(mode = "list", length = 5)
  nested_list[[i]] <- setNames(nested_list[[i]],c("ALL_SEASONS","SPRING","SUMMER","AUTUMN","WINTER"))
  for (j in 1:5) {
    nested_list[[i]][[j]] <- vector(mode="list",length=4)
    nested_list[[i]][[j]] <- setNames(nested_list[[i]][[j]],c("ALL_COMPANIES","COMPANY_1","COMPANY_2","COMPANY_3"))
  }
}

nested_list[["2014-2016"]][["ALL_SEASONS"]][["ALL"]] <- subset(df_ALL, YEAR >= 2014 & YEAR <= 2016)
nested_list[["2017-2019"]][["ALL_SEASONS"]][["ALL"]] <- subset(df_ALL, YEAR >= 2017 & YEAR <= 2019)
for (i in 1:2) {
  nested_list[[i]][["ALL_SEASONS"]][["COMPANY_1"]] <- subset(nested_list[[i]][["ALL_SEASONS"]][["ALL_COMPANIES"]],COMPANY == "COMPANY_1")
  nested_list[[i]][["ALL_SEASONS"]][["COMPANY_2"]] <- subset(nested_list[[i]][["ALL_SEASONS"]][["ALL_COMPANIES"]],COMPANY == "COMPANY_2")
  nested_list[[i]][["ALL_SEASONS"]][["COMPANY_3"]] <- subset(nested_list[[i]][["ALL_SEASONS"]][["ALL_COMPANIES"]],COMPANY == "COMPANY_3")
  
  for (k in 1:3) {
    nested_list[[i]][["SPRING"]][[k]] <- subset(nested_list[[i]][["ALL_SEASONS"]][[k]], SEASON == "SPRING")
    nested_list[[i]][["SUMMER"]][[k]] <- subset(nested_list[[i]][["ALL_SEASONS"]][[k]], SEASON == "SUMMER")
    nested_list[[i]][["AUTUMN"]][[k]] <- subset(nested_list[[i]][["ALL_SEASONS"]][[k]], SEASON == "AUTUMN")
    nested_list[[i]][["WINTER"]][[k]] <- subset(nested_list[[i]][["ALL_SEASONS"]][[k]], SEASON == "WINTER")
  }
}

有沒有更優雅的方式來創建嵌套列表? 還是創建嵌套列表而不是使用 lapply 的整個過程不是很值得推薦? 有什么替代方案?

您可以使用split ,它根據提供的函數創建列表。 在這里,我剛剛介紹了另一列使用年份並根據您的喜好命名的列。 然后,僅使用列名拆分其余部分。

df_ALL$split <- ifelse(df_ALL$YEAR > 2016, "2017-2019", "2014-2016")

nested_list <- lapply(split(df_ALL, df_ALL$split), function(x) {
  y <- split(x, x$SEASON)
  return(lapply(y, function(x) {
    split(x, x$COMPANY)
  }))
})

reprex 包(v0.3.0) 於 2020 年 11 月 5 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM