How to include strings and variables in the file path for read.csv in R?

邮差的信 提交于 2020-01-06 00:51:51

问题


I am trying to enter a file path into a function where part of the function reads data from .csv files from a folder specified in the function.

This part of the script:

prep_data <- function("filepath", Year_First, Year_Last)  {
...
FileName <- paste0(filepath,"/details", Year_Index, "moredetails", Year_Index, ".csv")
Tbl_Year <- read.csv(FileName)

Where

prep_data("/users/me/etc", 1980, 2014)

Is giving me this error:

In file(file, "rt") :
cannot open file 'filepath/details1980moredetails1980.csv': No such file or directory

My desired file path would be:

/users/me/etc/details1980moredetails1980.csv

This line is in a for loop that is reading .csv files for the range of specified years.


回答1:


read.csv(paste0(getwd(),'/details/, Year_Index, 'moredetails', Year_Index, '.csv'),header=TRUE,sep=',',FactorAsString=TRUE)

Suggest try getwd() for filepath if your files saved in directory.



来源:https://stackoverflow.com/questions/33249433/how-to-include-strings-and-variables-in-the-file-path-for-read-csv-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!