Leo96
Leo96

Reputation: 499

R:Using a character as argument in a function

I´m new here and I have not much knowledge in the use of R. I cant find a solution for my current problem: In the use of a character (Path) as an argument for my function.

Path <- "C:/...../"

foo <-function(Path){
       Driver  <- "Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=Path"
       connect <- odbcDriverConnect(Driver)
       return(connect)
}

My problem is, that Path will be replaced in the function with the quotes. At least I have the following format in my function.

...DBQ="C:/..../""

I tried to fix this problem with noquote or cat to delete the quotes, but it doesnt help.

I thank you in advance that you are helping a beginner in R :)

Upvotes: 0

Views: 96

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use sprintf() to insert the Path.

Path <- "C:/...../"
sprintf("Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=\"%s\"", Path)
# [1] "Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=\"C:/...../\""

So your updated function would be

foo <- function(Path) {
    Driver  <- "Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=\"%s\""
    connect <- odbcDriverConnect(sprintf(Driver, Path))
    return(connect)
}

See help(sprintf) for all its amazing uses.


Update: Since it's not clear to me whether you want the quotes around Path, I will include the way to have it without them. If you don't want the quotes in the string, remove them from the sprintf() format.

Path <- "C:/...../"
sprintf("Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=%s", Path)
# [1] "Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ=C:/...../"

Upvotes: 1

Related Questions