在一个目录下,我有多个具有相似格式的excel文件(您可以从以下位置下载示例文件)here https://www.dropbox.com/s/ho3visres55kpoy/test.zip?dl=0):
我需要
- 循环文件和
read_excel()
,
- 变异一个新列
name
与第二列名称,
- 将第一列和第二列重命名为
date
and value
分别删除最后一列(其原始列名是1
);
- 使用以下命令将所有 dfs 附加到一个数据帧
do.call(rbind, df.list)
我做了什么:
循环并获取文件路径:
library(fs)
folder_path <- './test/'
file_paths <- dir_ls(folder_path, regexp = ".xlsx")
读取excel的函数:
read_excel_file <- function(path) {
df <- read_excel(path = path, header = TRUE)
}
lapply read_excel()
每个 Excel 文件的函数:
df.list = lapply(file_paths, function(file) read_excel(file, skip = 2, col_names = FALSE))
df <- do.call(rbind, df.list)
预期结果将是这样的数据框:
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
我如何使用 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])
}
)
)
@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))`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)