Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using paste with read.csv inside a function

Tags:

r

read.csv

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?

like image 255
Victor Maxwell Avatar asked Apr 11 '26 05:04

Victor Maxwell


2 Answers

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)
like image 195
GKi Avatar answered Apr 12 '26 20:04

GKi


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()

like image 32
JMilner Avatar answered Apr 12 '26 20:04

JMilner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!