1. 如何分组处理20000个文件?
library(data.table)
library(tidyverse)
 
# 获取所有文件路径
files <- list.files("~/split_fa_res/", full.names = TRUE)
# 按200个一组切分
file_groups <- split(files, ceiling(seq_along(files) / 200))
 
# 输出目录
output_dir <- "~filtered_results/"
dir.create(output_dir, showWarnings = FALSE)
 
# 遍历每组
walk2(file_groups, seq_along(file_groups), function(group_files, i) {
    cat("Processing group", i, "\n")
    
    # 每组内部的数据处理
    s <- map(group_files, ~ {
        dat <- fread(.x, header = FALSE)
        if (nrow(dat) == 0) {
            return(NULL)
        }
        
        # 保存结果
        if (nrow(s) > 0) {
            fwrite(s, file = file.path(output_dir, paste0("filtered_group_", i, ".tsv")), sep = "\t")
        }
    })
  1. 如何直接传递变量?
library(dplyr)
library(rlang)
 
# ❌ 错误写法
my_summary_bad <- function(data, col) {
  data %>% summarise(mean = mean(col))
}
 
# ✅ 正确写法 1(rlang)
my_summary <- function(data, col) {
  col <- enquo(col)  # 捕捉未求值表达式
  data %>% summarise(mean = mean(!!col))  # 强制求值
}
 
my_summary(mtcars, mpg)
  1. 使用字符串构造变量名?
col_name <- "mpg"

# 用于编程方式引用变量
mtcars %>% mutate(new = !!sym(col_name) * 2)

# 或者更安全的版本:
col <- ensym(col_name)
mtcars %>% mutate(new = !!col * 2)
  1. 同时动态引用多个列?
cols <- syms(c("mpg", "hp"))
mtcars %>% select(!!!cols)
 
 
my_select <- function(data, ...) {
  data %>% select(...)
}
my_select(mtcars, mpg, hp)
  1. 如何判断每一列是否含有K00036的数字?
df <- data.frame(V1 = c("a", "b", "c"),
                 V2 = c("K00036", "NoCode", "K12345"))
 
# 判断是否有至少一行匹配
any_match <- any(grepl("K\\d{5}", df$V2))
print(any_match)  # TRUE