3

I want to create a function that uses read.csv() with paste(). The following code works in general

df <- read.csv(paste("/file name", 2010, ".CSV", sep = ""), header = TRUE)

but when I place it inside a function like so

myfunction <- function(date){df <- read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }

The command myfunction(2010) fails to produce output and does not result in any errors or warnings. What am I doing wrong?

Victor Maxwell
  • 306
  • 1
  • 12

3 Answers3

3

You need to use <<- instead of <-

myfunction <- function(date){df <<- read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }

or you write:

myfunction <- function(date){read.csv(
                             paste("/file name", date, ".CSV", sep = ""),
                             header = TRUE)
                            }
df <- myfunction(2000)
GKi
  • 37,245
  • 2
  • 26
  • 48
2

You could always use sprintf

myfunction <- function(date){
  df <- read.csv(sprintf('/filename%s.csv',date))
  return(df)
}
csv <- myfunction(date)

and if you have lots of dates

ListDates <- as.list(dates)
ListOfCsvs <- lapply(ListDates,myfunction)

EDIT: I didnt make it clear that your issue was solved by return(df) inside myfunction()

JMilner
  • 491
  • 4
  • 12
0

Return the dataframe from your function

myfunction <- function(date){
   df <- read.csv(paste("/file name", date, ".CSV", sep = ""),header = TRUE)
   return(df)
}

and assign it

df <- myfunction(2010)

In R, the last line in the function is automatically returned anyway, so this should also work.

myfunction <- function(date){
   read.csv(paste("/file name", date, ".CSV", sep = ""),header = TRUE)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213