提取具有特定名称的变量并循环所有文件

Extract variables with specific names and loop for all files

目的是 (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) frame 和 (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文件。

我们使用 selectselect_helpers 就像 starts_with

library(dplyr)
df1 %>% 
     select(frame, starts_with('unit'))

-输出

#   frame unit_1 unit_2 unit_3
#1     1      1      0      0
#2     2      1      0      0
#3     3      1      0      0
#4     4      1      0      0
#5     5      1      0      0

matches 中的正则表达式以匹配以 (^) 开头的模式与子字符串 'unit' 后跟 _ 和一个或多个数字 (\d+) 在字符串的末尾 ($) 作为列名

df1 %>%
      select(frame, matches('^unit_\d+$'))

如果是data.frame的list,用[=27=循环list,用read_csv读取文件,select 感兴趣的列并使用 write_csv

在前缀为 'new_' 的同一目录中创建新文件
library(purrr)
library(readr)
library(stringr)
walk(files, ~ read_csv(file.path("C:/files", .x)) %>%
               select(frame, starts_with('unit')) %>%
               write_csv(file.path("C:/files", str_c("new_", .x)))
       )

base R 中的等效选项是 startsWith

subset(df1, select = c('frame',
          names(df1)[startsWith(names(df1), 'unit')]))

grep

subset(df1, select = grep('^(frame|unit)', names(df1), value = TRUE))

以及 list 个文件

lapply(files, function(x) {
      tmp <-  subset(read.csv(file.path("C:/files", x)),
              select = grep('^(frame|unit)', names(df1), value = TRUE))
    write.csv(tmp, file.path("C:/files", paste0("new_", x)), 
                 row.names = FALSE, quote = FALSE)
    })