循环过程以统一 R 中的差异 excel
Loops for process to unificate differents excel in R
我想用不同的 Excel 文件重复这个过程,我想为此做一个循环,但我不知道从哪里开始。
# Route in excel
path <- "mar_2016.xls"
# Unificate data for Sheet
data_mar16 = path %>%
excel_sheets() %>%
set_names() %>%
map_df(~ read_excel(path = path, sheet = .x), .id = "Sheet")
# Select columns
data_mar16 <- data_mar16%>% select("Sheet","F_H","PE_H", "NO")
# Filter values of column Sheet
data_mar16 <- filter(data_mar16, Sheet %in% c("A", "C", "B" ))
# Save the data
write_xlsx(data_mar16, "mar16.xlsx")
有什么想法吗?
因为没有测试数据,所以我把它写在了一个文本文件中...所以可能有错别字:
# Route to multiple excel files
paths <- c("mar_2016.xls", "mar_2017.xls")
# run a loop for the length of your char vector with files
for (i in 1:length(paths)){
# select position from vector acording to loop index
file <- paths[i]
# Unificate data for Sheet
data <- excel_sheets(file) %>%
set_names() %>%
map_df(~ read_excel(path = file, sheet = .x), .id = "Sheet") %>%
select("Sheet","F_H","PE_H", "NO") %>%
filter(Sheet %in% c("A", "C", "B" ))
# Save the data
write_xlsx(data, file)
}
另一种选择是将代码转换为函数,然后通过 map() 将其应用于向量(或在 map 调用中将其全部写入)。
我想用不同的 Excel 文件重复这个过程,我想为此做一个循环,但我不知道从哪里开始。
# Route in excel
path <- "mar_2016.xls"
# Unificate data for Sheet
data_mar16 = path %>%
excel_sheets() %>%
set_names() %>%
map_df(~ read_excel(path = path, sheet = .x), .id = "Sheet")
# Select columns
data_mar16 <- data_mar16%>% select("Sheet","F_H","PE_H", "NO")
# Filter values of column Sheet
data_mar16 <- filter(data_mar16, Sheet %in% c("A", "C", "B" ))
# Save the data
write_xlsx(data_mar16, "mar16.xlsx")
有什么想法吗?
因为没有测试数据,所以我把它写在了一个文本文件中...所以可能有错别字:
# Route to multiple excel files
paths <- c("mar_2016.xls", "mar_2017.xls")
# run a loop for the length of your char vector with files
for (i in 1:length(paths)){
# select position from vector acording to loop index
file <- paths[i]
# Unificate data for Sheet
data <- excel_sheets(file) %>%
set_names() %>%
map_df(~ read_excel(path = file, sheet = .x), .id = "Sheet") %>%
select("Sheet","F_H","PE_H", "NO") %>%
filter(Sheet %in% c("A", "C", "B" ))
# Save the data
write_xlsx(data, file)
}
另一种选择是将代码转换为函数,然后通过 map() 将其应用于向量(或在 map 调用中将其全部写入)。