我有幾個 excel 檔案 (*.xlsx),每個檔案都有很多張。我想從每個檔案創建一個嵌套串列。盡管我可以使用以下代碼為每個檔案單獨執行此操作。
g1 <- file1 %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = file1)
但是,如果我必須g1, g2, g3, g4, g5為 5 個 excel 檔案創建一些 5 個嵌套串列。然后我必須為每個變數撰寫上述代碼 5 次。我們可以使用for loop迭代list.files來減少行數。
我需要嵌套串列,因為我會在稍后階段合并它們。
我做了如下粗略的嘗試:
files <- list.files(pattern = "*.xlsx")
for (i in 1:length(files)){
"g"[i] <- files[i] %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = files[i])
}
但這不起作用。
uj5u.com熱心網友回復:
也許它會很有用
library(tidyverse)
library(readxl)
path <- here::here("source", "xlsx")
list_files <- fs::dir_ls(path)
tibble(files = list_files) %>%
mutate(sheets = map(files, excel_sheets)) %>%
unnest(sheets) %>%
mutate(data = map2(files, sheets, read_xlsx))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394820.html
上一篇:在R中合并具有相同標題的幾列
