使用Lapply函数从Excel导入数据
由于原始的STATA命令,我试图从150个不同文件中导入数据,该命令没有附加功能或与OuterG2命令兼容。我决定将其带到R,因为我更熟悉在那里导入和导出。
每个.xlsx文件完全相同 格式仅在值和标签描述中更改。正好有150个。
到目前为止,我已经管理了:
#library(readxl)
file.list <- list.files(pattern='*.xlsx', recursive = TRUE)
df.list <- lapply(file.list, read_excel)
#library(dplyr)
df1 <- bind_rows(df.list, .id= "id")
这将返回一个数据框,如下所示: 事件研究结果表1 。完全按照我想要的结果。
但是,lapply命令读取的文件还保存了编号2,3,我想以类似的方式导入该文件(创建图片中所示的附加表)。简单地将功能调整为:
df.list2 <- lapply(file.list, read_excel(sheet = 2))
可悲的是行不通,要求我添加“路径”参数。添加它:
df.list2 <- lapply(file.list, read_excel(path = "D:/sietse/Documents/RUG/Master/Thesis/Data/STATA", sheet = 2))
给我错误:
文件中的错误(con,“ rb”):无法打开连接 另外:警告消息: 在文件中(con,“ rb”): 无法打开文件'd:/sietse/documents/lug/master/stesis/data/stata':拒绝许可
在进行一些研究之后,我知道这与文件名的规范有关;指定任何文件名都会违反功能开始的目的,并为我提供大量的手动工作。
有人知道如何解决这个问题还是更好的方法?非常感谢。
I am trying to import data from 150 different files due to a primitive STATA command which doesn't have an append functionality or is compatible with the outreg2 command. I decide to take it to R since I am more familiar with importing and exporting there.
Each .xlsx file holds the exact same
format only changing in values and label description. There are exactly 150 of them.
So far I managed:
#library(readxl)
file.list <- list.files(pattern='*.xlsx', recursive = TRUE)
df.list <- lapply(file.list, read_excel)
#library(dplyr)
df1 <- bind_rows(df.list, .id= "id")
This returns a dataframe like seen below:
Event study results sheet 1. Which is exactly as I want it to turn out.
However, the files the lapply command reads, also hold sheet number 2,3, and 4 which I would like to import in a similar fashion (create appended tables as seen in the picture). Simply adjusting the function to:
df.list2 <- lapply(file.list, read_excel(sheet = 2))
Sadly doesn't work and requires me to add a "path" argument. Adding it:
df.list2 <- lapply(file.list, read_excel(path = "D:/sietse/Documents/RUG/Master/Thesis/Data/STATA", sheet = 2))
Gives me the error:
Error in file(con, "rb") : cannot open the connection
In addition: Warning message:
In file(con, "rb") :
cannot open file 'D:/sietse/Documents/RUG/Master/Thesis/Data/STATA': Permission denied
After some research I know that this has to do with specification of file names, however; specifying any filename would defeat the purpose of the function to begin with and leaves me with a lot of manual work.
Does anyone know how to solve this or a better way to approach it? Much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将表格添加为这样的参数:
或这样,这样:
You can add the sheet as a param like this:
Or, like this: