【发布时间】:2021-05-26 05:52:38
【问题描述】:
目的是 (1) 提取具有特定名称的变量(列) (2) 循环文件夹中的所有文件以及 (3) 将输出保存在 csv 文件中。
例如,一个文件的数据看起来像:
structure(list(frame = c(1, 2, 3, 4, 5), g_1 = c(0.1, 0.2, 0.1,
0, 0), g_2 = c(0, 0, 0, 0, 0), xy_1 = c(0.4, 0.43, 0.32, 0.33,
0.39), xy_2 = c(0, 0, 0, 0, 0.1), unit_1 = c(1, 1, 1, 1, 1),
unit_2 = c(0, 0, 0, 0, 0), unit_3 = c(0, 0, 0, 0, 0)), class = "data.frame", row.names = c(NA,
-5L), variable.labels = structure(character(0), .Names = character(0)), codepage = 65001L)
对于每个数据集,我只需要变量 (1) 框架和 (2) 以“unit_”开头的变量。所以我需要为每个文件获取并保存在 csv 中的输出如下所示:
╔═══════╦════════╦════════╦════════╗
║ frame ║ unit_1 ║ unit_2 ║ unit_3 ║
╠═══════╬════════╬════════╬════════╣
║ 1.00 ║ 1.00 ║ .00 ║ .00 ║
╠═══════╬════════╬════════╬════════╣
║ 2.00 ║ 1.00 ║ .00 ║ .00 ║
╠═══════╬════════╬════════╬════════╣
║ 3.00 ║ 1.00 ║ .00 ║ .00 ║
╠═══════╬════════╬════════╬════════╣
║ 4.00 ║ 1.00 ║ .00 ║ .00 ║
╠═══════╬════════╬════════╬════════╣
║ 5.00 ║ 1.00 ║ .00 ║ .00 ║
╚═══════╩════════╩════════╩════════╝
我想知道是否有办法使用 dplyr 或其他方法来做到这一点。
我在想:
files <- list.files(path="C:/files", pattern="csv")
out <- lapply(files, function(file) {
dat <- data.frame(fread(paste0("C:/files/", file) ) )
dat <- dat[c("frame", "unit_1", "unit_2", "unit_3")]})
从这里开始,我不清楚如何将每个文件保存到 csv 文件中。
【问题讨论】:
标签: r dplyr data.table tidyr