如何在 R 中 read.csv 的文件路径中包含字符串和变量?

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

我正在尝试将文件路径输入到函数中,其中部分函数从函数中指定的文件夹中的 .csv 文件中读取数据。

这部分脚本:

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

在哪里

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

给我这个错误:

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

我想要的文件路径是:

/users/me/etc/details1980moredetails1980.csv

此行位于读取指定年份范围内的 .csv 文件的 for 循环中。

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

如果您的文件保存在目录中,建议尝试使用 getwd() 作为文件路径。