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?
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With