我有一个文件夹,里面有500多个.dta文件。我想将其中的一些文件加载到一个R对象中。
我的.dta文件的通用名称由四个部分组成:‘两个字母/四个数字/y/.dta’。例如,名称可以是'de2015y.dta‘或'fr2008y.dta’。在整个.dta文件中,只有与两个字母和四个数字相对应的部分才会更改。
我已经写了一个可以工作的代码,但我对它并不满意。我想避免使用循环,并缩短它。
我的代码是:
# Select the .dta files I want to load
#.....................................
name <- list.files(path="E:/Folder") # names of the .dta files in the folder
db <- as.data.frame(name)
db$year <- substr(db$name, 3, 6)
db <- subset (db, year == max(db$year)) # keep last year available
db$country <- substr(db$name, 1, 2)
list.name <- as.list(db$country)
# Loading all the .dta files in the Global environment
#..................................................
for(i in c(list.name)){
obj_name <- paste(i, '2015y', sep='')
file_name <- file.path('E:/Folder',paste(obj_name,'dta', sep ='.'))
input <- read.dta13(file_name)
assign(obj_name, value = input)
}
# Merge the files into a single object
#..................................................
df2015 <- rbind (at2015y, be2015y, bg2015y, ch2015y, cy2015y, cz2015y, dk2015y, ee2015y, ee2015y, es2015y, fi2015y,
fr2015y, gr2015y, hr2015y, hu2015y, ie2015y, is2015y, it2015y, lt2015y, lu2015y, lv2015y, mt2015y,
nl2015y, no2015y, pl2015y, pl2015y, pt2015y, ro2015y, se2015y, si2015y, sk2015y, uk2015y)有人知道如何避免使用循环和缩短代码吗?
发布于 2017-04-27 18:33:15
您还可以使用purrr执行任务。
首先为你想要加载的所有文件创建一个命名向量(我理解你的问题,你只需要2015年的所有文件)。仅当您希望在数据框中包含ID变量,并且.dta文件中尚未包含ID变量时,才需要setNames()部件。
在此之后,只需使用map_df()读取所有文件并返回一个数据帧。指定.id是可选的,它会产生一个ID列,该列的值基于in_files的名称。
library(purrr)
library(haven)
in_files <- list.files(path="E:/Folder", pattern = "2015y", full.names = TRUE)
in_files <- setNames(in_files, in_files)
df2015 <- map_df(in_files, read_dta, .id = "id") 发布于 2017-04-27 16:45:38
我将更改此任务的工作目录...那么这能满足你的要求吗?
setwd("C:/.../yourfiles")
# get file names where year equals "2015"
name=list.files(pattern="*.dta")
name=name[substr(name,3,6)=="2015"]
# read in the files in a list
files=lapply(name,foreign::read.dta)
# remove ".dta" from file names and
# give the file contents in the list their name
names(files)=lapply(name,function(x) substr(x, 1, nchar(x)-4))
#or alternatively
names(files)=as.list(substr(name,1,nchar(name)-4))
# optional: put all file contents into one data-frame
#(data-frames (vectors) need to have the same row counts (lengths) for this last step to work)
mydatafrm = data.frame(files)发布于 2017-04-27 16:59:31
以下步骤将为您提供所需的内容:
foreign包:library(外部)#或者: library(haven)
file.list <- list.files(path="E:/Folder",pattern='*.dat',full.names =list.files要读取的文件(注意:您必须检查这些文件在substr中的位置是否正确,这是我的估计)
vec <- file.listvec==max(vec)
simplify=FALSE)
names(df.list))
库(data.table) df <- rbindlist(df.list,idcol = "id") #或与'dplyr‘库(Dplyr) df <- bind_rows(df.list,.id = "id")
现在,您有了一个带有标识不同原始文件的id列的data.frame。
https://stackoverflow.com/questions/43651744
复制相似问题