我有一个excel文件文件夹,每个文件夹包含多张工作表.每个wb中的图纸名称相同.我正在try 将所有excel文件的一个特定命名工作表作为单独的数据框导入.我已经能够将它们导入;但是,名称变为df\u 1、df\u 2、df\u 3等...我一直在try 使用excel文件名的第一个单词来识别df.

Excel文件名"AAPL Multiple Sheets"的示例我正在将该表命名为"Balance",作为df导入.我想要"AAPL Balance df"作为结果.

最接近我要查找的代码位于下面,但它将每个数据帧命名为df\u 1、df\u 2,依此类推.

library(purrr)
library(readxl)

files_list <- list.files(path = 'C:/Users/example/Drive/Desktop/Total_Related_Data/Analysis of Data/',
pattern = "*.xlsx",full.names = TRUE)

files_list %>% 
    walk2(1:length(files_list),
          ~ assign(paste0("df_", .y), read_excel(path = .x), envir = globalenv()))

我try 在past0函数中使用文件路径变量"file\u list"来标记它们,结果是,

df\u C:/Users/example/Drive/Desktop/Total\u Related\u Data/Analysis of Data/.xlsx1,df\u C:/Users/example/Drive/Desktop/Total\u Related\u Data/Analysis of Data/.xlsx2,

等等

我试着列出要使用的文件名.这读取了文件名并创建了一个列表,但我无法使用上面的代码.

files_Names<-list.files(path='C:/Users/example/Drive/Desktop/Total_Related_Data/Analysis of Data/', pattern=NULL, all.files=FALSE, full.names=FALSE)

结果是,

推荐答案

您可以执行以下操作(请注意,我使用openxlsx包读取Excel文件,但您当然可以用readxl替换该部分):

library(openxlsx)
library(tidyverse)

Starting with your `files_list` we can do:

# using lapply to read in all files and store them as list elements in one list
list_of_dfs <- lapply(as.list(files_list), function(x) readWorkbook(x, sheet = "Balance"))

# Create a vector of names based on the first word of the filename + "Balance"
# Note that we can't use empty space in object names, hence the underscore
df_names <- paste0(str_extract(basename(files_list), "[^ ]+"), "_Balance_df")

# Assign the names to our list of dfs
names(list_of_dfs) <- df_names

# Push the list elements (i.e. data frames) to the Global environment
# I highly recommend NOT doing this. I'd say in 99% of the cases it's better to continue working in the list structure or combine the individual dfs into one large df.
list2env(list_of_dfs, env = .GlobalEnv)

R相关问答推荐

Facet_wrap具有不同bin宽度值的图表

如何创建具有总计列和ggplot 2所有条线的百分比标签的堆叠条形图?

提取rame中对应r中某个变量的n个最小正值和n个最大负值的条目

无法运行通过R中的Auto.arima获得的ARIMA模型

geom_Ribbon条件填充创建与数据不匹配的形状(ggplot 2 r)

如何对数据集进行逆向工程?

如何自定义Shapviz图?

在for循环中转换rabrame

如何使下一个按钮只出现在Rshiny 的一段时间后?""

如何根据R中其他列的值有条件地从列中提取数据?

使用外部文件分配变量名及其值

给定开始日期和月份(数字),如何根据R中的开始日期和月数创建日期列

如何将网站图像添加到带有极坐标的面包裹条形图?

您是否可以将组添加到堆叠的柱状图

按组计算列中1出现的间隔年数

从多个可选列中选取一个值到一个新列中

数值型数据与字符混合时如何进行绑定

对R中的列表列执行ROW Mean操作

roxygen2正在处理太多的文件

在使用ggplot2的情况下,如何在使用coord_trans函数的同时,根据未转换的坐标比来定位geom_瓷砖?