如何阅读R中的文件夹内的csv? [英] How to read csv inside a folder in R?

查看:174
本文介绍了如何阅读R中的文件夹内的csv?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个目录中工作,但是我想要读取的数据在一个子目录中。当我尝试读取csv文件时出现错误,我的代码如下:

  setwd(〜/ Documents / )
文件< - list.files(path =data /)
f< - list()
for(i in 1:length(files)){
f [[i]] < - read.csv(files [i],header = T,sep =;)
}

我得到的错误是:

文件(文件,rt)错误:无法打开连接

解决方案

假设你已经正确指定了其他的read.csv参数,

  setwd(〜/ Documents /)
files< - list.files(path =data / )
f< - list()
for(in 1:length(files)){
f [[i]] < - read.csv(paste0(data / ,文件[i]),header = T,sep =;)
}

或者,您可以删除 paste0 ,并简单地将您的工作目录设置为〜/ Documents / data / 地点。

  setwd(〜/ Documents / data /)
文件< - list.files()#No因为你在正确的目录
f< - list()
for(i in 1:length(files)){
f [[i]]< - read .csv(files [i],header = T,sep =;)
}



<如果你需要在这个循环结束时在〜/ Documents / 中,那么在循环之后添加以下内容就可以完成它了。

  setwd(〜/ Documents /)


I am working in a directory, but the data I want to read is in a subdirectory. I get an error when I try to read the csv files, my code is the following:

setwd("~/Documents/")
files <- list.files(path = "data/")
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(files[i], header = T, sep = ";")
}

And the error I get is:

Error in file(file, "rt"): cannot open the connection

What am I doing wrong?

解决方案

The following will work, assuming you have correctly specified the other read.csv parameters.

setwd("~/Documents/")
files <- list.files(path = "data/")
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(paste0("data/",files[i]), header = T, sep = ";")
}

Alternatively, you could drop the paste0 and simply set your working directory to ~/Documents/data/ in the first place.

setwd("~/Documents/data/")
files <- list.files() #No parameter necessary now since you're in the proper directory
f <- list()
for (i in 1:length(files)) {
  f[[i]] <- read.csv(files[i], header = T, sep = ";")
}

If you need to be in ~/Documents/ at the end of this loop, then finish it up by adding the following after the loop.

setwd("~/Documents/")

这篇关于如何阅读R中的文件夹内的csv?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆