2
votes

I'm struggling with an R tutorial.

The goal is to create a function that must: 1) Set the working directory to a folder on my desktop that contains numerous .csv files. 2) Take a parameter to identify which file to use/load. 2b) The parameter must be made into a particular format. The person calling the function could enter a number between 1 and three digits in length). There are a few hundred potential files to load and they must be output with the format "001.csv", "050.csv" and "200.csv". 3) Load the data of the entered file.

Here is my code:

getmonitor <- function(id){

setwd("C:/Users/myname/Desktop/specdata") #set the directory

csvfile <- function(id) # set the file number format
    if (id < 10) { 
        paste0(0,0,id,".csv")
    } else if (id < 100) {
        paste0(0,id,".csv")
    } else paste0(id,".csv")
}

foo <-read.csv(csvfile) #load the appropriate csv file

}

Well that didn't work. The error message I got was this: "Error in read.table(file = file, header = header, sep = sep, quote = quote, : 'file' must be a character string or connection"

I have done a fair amount of Googling around and cannot understand how to resolve this. Is my approach OK? I am new to R and to programming in general.

1

1 Answers

3
votes

You are passing the function csvfile as the file argument, not the string that that function returns when called. You want

foo <- read.csv(csvfile(id))