【问题标题】:save R for loop results in different folder将 R for 循环结果保存在不同的文件夹中
【发布时间】:2014-09-09 15:03:36
【问题描述】:

我的目标是对文件夹(C:\sample)中的每个文件应用一组代码,然后将处理后的数据保存到另一个文件夹(C:\cleaned)。我从这里的其他帖子中学习(非常感谢!)并为我的案例编写了代码:

files <- list.files(path="C:\\sample", pattern="*.CSV", full.names=T, recursive=FALSE)
datalist <- lapply(files, function(x) {
t <- read.csv(x, header=T, na.string=c("", "null","NaN"),stringsAsFactors=FALSE) # load file
t[ , c(4:10)]<- sapply(t[ , c(4:10)], as.numeric)
t <- t[!is.na(t$Node.1),]
})

for( i in 1:length(files)){
write.csv(datalist[[i]] , files[[i]] ,row.names=F )
}

通过运行我当前的代码,结果将替换文件夹“C:\sample”中的原始文件。我怎样才能稍微修改一下代码,以便将每个处理过的文件保存在另一个文件夹“C:\cleaned”中?

谢谢!

【问题讨论】:

    标签: r loops for-loop lapply


    【解决方案1】:

    使用full.names=T 会将路径添加到文件名中,这对您正在执行的操作很不方便。

    处理这个问题的最好方法是设置你的工作目录

    setwd("C:\\sample")
    

    然后列出你的文件

    files <- list.files("C:\\sample", pattern="*.CSV")
    

    然后您可以附加所需的路径

    write.csv(datalist[[i]] , paste0("C:\\cleaned\", files[[i]]), 
              row.names=F)
    

    或更改工作目录并直接使用文件名

    setwd("C:\\cleaned")
    write.csv(datalist[[i]] , files[[i]], row.names=F)
    

    【讨论】:

    • 谢谢。但是输出报错:Error in file(file, ifelse(append, "a", "w")) : cannot open the connection 另外:警告信息: In file(file, ifelse(append, "a", " w")) : 无法打开文件 'C:\cleaned\C:\sample/N1_07252014.CSV': 无效参数
    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2021-05-04
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多