如何遍历目录中的CSV文件并将其输出为RDS文件

时间:2019-02-25 14:44:33

标签: r dataset

这是我现在拥有的代码,我不断收到错误消息,未定义fd,我尝试将其定义为 fd = data.frame() 但这不起作用。

代码:

file<-list.files(pattern=".csv$")  
#file creates a list of csv file names 

for (i in seq_along(filenames))

{
 fd[i]<- read.csv(file[i]) 

#read each csv file
output=c("o1.RDS","o2.RDS","o3.RDS")

#save each csv file as RDS every iteration, 
#with the name as specified in the vector output.

saveRDS(fd[i],file =output[i])     

}

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作,尽管它未经测试,因为目前我没有.csv文件的文件夹:

library(tidyverse)

files <- list.files("./", pattern = ".csv")

map(files, ~read_csv(.x) %>% 
      write_rds(path = paste0("YOUR/PATH/HERE", basename(.x), ".rds")))

答案 1 :(得分:0)

您是否尝试过将fd定义为列表?

fd <- list()

在上面的示例中,您还犯了一个错误。应该是“文件名”而不是“文件”。

这是对我有用的结果:

fd <- list()

file <- list.files(pattern=".csv$")  
#file creates a list of csv file names 

for (i in seq_along(file))

{
        fd[i]<- read.csv(file[i]) 

        #read each csv file
        output = c("o1.RDS","o2.RDS","o3.RDS")

        #save each csv file as RDS every iteration, 
        #with the name as specified in the vector output.

        saveRDS(fd[i], file = output[i])     

}