简体   繁体   中英

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

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:/...../"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM