ahb*_*bon 3 r lapply dplyr readxl
在一个目录下,我有多个具有相似格式的excel文件(您可以从这里下载示例文件):
我需要
read_excel(),name使用第二列名称改变新列,date和value,删除最后一列(其原始列名为1);do.call(rbind, df.list)我做了什么:
循环并获取文件路径:
library(fs)
folder_path <- './test/'
file_paths <- dir_ls(folder_path, regexp = ".xlsx")
Run Code Online (Sandbox Code Playgroud)
读取excel的函数:
read_excel_file <- function(path) {
df <- read_excel(path = path, header = TRUE)
}
Run Code Online (Sandbox Code Playgroud)
lapplyread_excel()函数到每个 Excel 文件:
df.list = lapply(file_paths, function(file) read_excel(file, skip = 2, col_names = FALSE))
df <- do.call(rbind, df.list)
Run Code Online (Sandbox Code Playgroud)
预期结果将是这样的数据框:
date value name
2 2021-01-07 -76.5 J05-J01
3 2021-01-08 -93.5 J05-J01
4 2021-01-15 -305 J05-J01
5 2021-01-22 289 J05-J01
6 2021-01-29 242.5 J05-J01
7 2021-02-05 266 J05-J01
8 2021-02-10 239.5 J05-J01
9 2021-02-19 305.5 J05-J01
10 2021-01-07 323 J01-J09
11 2021-01-08 317.5 J01-J09
12 2021-01-15 527.5 J01-J09
13 2021-01-22 -51 J01-J09
14 2021-01-29 -58.5 J01-J09
15 2021-02-05 -76 J01-J09
16 2021-01-07 76.5 J01-J05
17 2021-01-08 93.5 J01-J05
18 2021-01-15 305 J01-J05
19 2021-01-22 -289 J01-J05
20 2021-01-29 -242.5 J01-J05
21 2021-02-05 -266 J01-J05
22 2021-02-10 -239.5 J01-J05
Run Code Online (Sandbox Code Playgroud)
我怎样才能使用 R 实现这一目标?提前非常感谢。
library(dplyr)
library(readxl)
files <- list.files()
combined <- bind_rows(
lapply(
files,
function(f) {
df <- read_xlsx(f)
df %>%
select(date = 1, value = 2) %>%
mutate(name = colnames(df)[2])
}
)
)
Run Code Online (Sandbox Code Playgroud)
@ah bon 的替代方案:
read_file <- function(file) {
df <- read_xlsx(file)
df <- df %>%
select(date = 1, price = 2) %>%
mutate(name = colnames(df)[2])
return(df)
}
df <- bind_rows(
lapply(
files,
read_file
)
)
# or `df <- do.call(rbind, lapply(files, read_file))`
Run Code Online (Sandbox Code Playgroud)