r 循环遍历R中的文件并应用函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r 循环遍历R中的文件并应用函数相关的知识,希望对你有一定的参考价值。

#perform a function on each file
#https://www.r-bloggers.com/perform-a-function-on-each-file-in-r/


setwd("H:/sample")
list.files("H:/sample")

fileNames<-Sys.glob("*.csv")
fileNames


for (fileName in fileNames) {
  
  # read data:
  sample <- read.csv(fileName,
                     header = TRUE,
                     sep = ",")
  
  # add more stuff here
  
}



for (fileName in fileNames) {
  
  # read old data:
  sample <- read.csv(fileName,
                     header = TRUE,
                     sep = ",")
  
  # add one to every widget value in every file:
  sample$Widgets <- sample$Widgets + 1
  
  # overwrite old data with new data:
  write.table(sample, 
              fileName,
              append = FALSE,
              quote = FALSE,
              sep = ",",
              row.names = FALSE,
              col.names = TRUE)
  
}



extension <- "csv"

fileNames <- Sys.glob(paste("*.", extension, sep = ""))

fileNumbers <- seq(fileNames)

for (fileNumber in fileNumbers) {
  
  newFileName <-  paste("new-", 
                        sub(paste("\\.", extension, sep = ""), "", fileNames[fileNumber]), 
                        ".", extension, sep = "")
  
  # read old data:
  sample <- read.csv(fileNames[fileNumber],
                     header = TRUE,
                     sep = ",")
  
  # add one to every widget value in every file:
  sample$Widgets <- sample$Widgets + 1
  
  # write old data to new files:
  write.table(sample, 
              newFileName,
              append = FALSE,
              quote = FALSE,
              sep = ",",
              row.names = FALSE,
              col.names = TRUE)
  
}



fileNames <- Sys.glob("*.csv")

for (fileName in fileNames) {
  
  # read original data:
  sample <- read.csv(fileName,
                     header = TRUE,
                     sep = ",")
  
  # create new data based on contents of original file:
  allWidgets <- data.frame(
    File = fileName,
    Widgets = sum(sample$Widgets))
  
  ##YOU could definitely use this for the SIC thing! 
  
  # write new data to separate file:
  write.table(allWidgets, 
              "Output/sample-allSamples.csv",
              append = TRUE,
              sep = ",",
              row.names = FALSE,
              col.names = FALSE)
  
}

以上是关于r 循环遍历R中的文件并应用函数的主要内容,如果未能解决你的问题,请参考以下文章

R:循环遍历目录中的所有文件,应用列替换命令

循环遍历 R 中的列并提取字符

循环遍历 netcdf 文件并运行计算 - Python 或 R

在 R 中使用 RODBC 创建循环 SQL QUERY

R函数从网络中一个一个地删除节点并输出最大的连通分量

Python中的用for,while循环遍历文件实例