在R中读取多个CSV文件作为数据帧

时间:2017-10-02 02:29:59

标签: r csv

我一直在试图解决这个问题,我已经阅读了很多博客并尝试了不同的东西,但我仍然遇到同样的错误,而且我不明白我的代码有什么问题。我我试图将几个csv文件同时拉入R并且我不断收到以下错误。

  

文件中没有此类文件或directoryError(文件," rt"):无法打开连接

`Tea_ONE <- "~/Desktop/Circadian Rhythms 
   Sem/Project/Tea_Party_ONE/Tea_Party_ONE_Lumicycle_data/"

      files <- list.files(path = Tea_ONE, pattern = ".csv$")

 for(i in 1:length(files)){
     assign(files[i],
     read.csv(paste(Tea_ONE, files[i], header = T, skip = 1)))
  }`

所有CSV文件都位于Tea_Party_ONE_Lumicycle_data中。

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

正如评论中提到的,问题是paste0正在添加空格分隔符。您可以使用library('tidyverse') files <- list.files(path = Tea_ONE, pattern = '.csv$', full.names = T) %>% map(read_csv, skip = 1) ,也可以获取完整路径名称。

push

答案 1 :(得分:2)

有很多方法!!

setwd("C:/your_path_here")
fnames <- list.files()
csv <- lapply(fnames, read.csv)
result <- do.call(rbind, csv)


********  ********  ********  ********  ********  ********  ********  ********  ********  ********  


filedir <- setwd("C:/your_path_here")
file_names <- dir(filedir)
your_data_frame <- do.call(rbind,lapply(file_names,read.csv))


********  ********  ********  ********  ********  ********  ********  ********  ********  ********  


filedir <- setwd("C:/your_path_here")
file_names <- dir(filedir)
your_data_frame <- do.call(rbind, lapply(file_names, read.csv, skip = 1, header = FALSE))


********  ********  ********  ********  ********  ********  ********  ********  ********  ********  


filedir <- setwd("C:/your_path_here")
file_names <- dir(filedir)
your_data_frame <- do.call(rbind, lapply(file_names, read.csv, header = FALSE))


********  ********  ********  ********  ********  ********  ********  ********  ********  ******** 


# 
temp <- setwd("C:/your_path_here")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)


********  ********  ********  ********  ********  ********  ********  ********  ********  ******** 


# Here is another options to convert the .csv files into one data.frame. Using R base functions. 
# This is order of magnitude slower than the options below.

files <- setwd("C:/your_path_here")
# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()


********  ********  ********  ********  ********  ********  ********  ********  ********  ******** 


# LIST OF FILE PATHS

library(readr)
library(stringr)

List_of_file_paths <- list.files(path ="C:/your_path_here/", pattern = ".csv", all.files = TRUE, full.names = TRUE)


********  ********  ********  ********  ********  ********  ********  ********  ********  ********


# LIST OF FILES IN FOLDER
xlist<-list.files(pattern = "*.csv")

for(i in xlist) { 
  x <- read.csv((i))
  assign(i, x)
    }


********  ********  ********  ********  ********  ********  ********  ********  ********  ********