首页 > 解决方案 > 如何遍历R中的dta文件文件夹

问题描述

我目前正在尝试将几个调查数据集垂直合并到一个大数据集中。数据集位于我桌面上的一个文件夹中,采用 dta 格式。请问我该怎么做?

标签: rloops

解决方案


我认为 data.table 包可以很容易地折叠存储在列表中的数据框:

library(haven)
library(data.table)

d1 <- data.frame(x = rpois(10, 13))
d2 <- data.frame(x = rpois(10, 13))
write_dta(d1, "1993.dta")
write_dta(d2, "1994.dta")

# get the file names
files <- list.files(pattern = "\\.dta$")

# write a function that reads in the data, and transforms it into a data.table object
open.files <- function(x){ setDT(read_dta(x)) }

# read in the files in a list and name the list
d <- lapply(files, open.files)
names(d) <- files

# rbind all the data.frames
d <- rbindlist(d, idcol = "filename", use.names = T)
d
     filename  x
 1: 1993.dta 10
 2: 1993.dta 13
 3: 1993.dta 14
 4: 1993.dta 13
 5: 1993.dta 12
 6: 1993.dta 17
 7: 1993.dta 12
 8: 1993.dta 18
 9: 1993.dta 11
10: 1993.dta 13
11: 1994.dta 13
12: 1994.dta 12
13: 1994.dta 15
14: 1994.dta 11
15: 1994.dta 11
16: 1994.dta  7
17: 1994.dta 16
18: 1994.dta 10
19: 1994.dta 11
20: 1994.dta 15

或者,看看这里:将数据帧列表转换为一个数据帧


推荐阅读