Home > Blockchain >  Function parameter within a string
Function parameter within a string

Time:11-01

I would like to put a parameter within a string in order to import a file with this function:

import_df <- function(df) {
  df <- read_xpt(
    file = "C:\\Folder\\Sub1\\Sub2\\df.xpt"
  )
  return(df)
}

import_df(ds1)

Problem is each time I get this message: Error: 'C:\folder\Sub1\Sub2\df.xpt' does not exists. It does not consider "df" as "ds1" in the file path. How can I do it with a R function?

CodePudding user response:

You’ll have the same issue with any variable, not just function parameters. A string literal is fundamentally different from code. If it weren’t, how would R be supposed to know that you intend df to be a variable? Why not also C, Folder, Sub1, Sub2 and xpt?

You’ll need to tell R to construct your string from different parts. There are different ways of doing this; the most basic is paste0:

paste0("C:\\Folder\\Sub1\\Sub2\\", df, ".xpt")

Another frequently used way is sprintf, which is mainly useful for people who are familiar with other languages, such as C. Otherwise, you could install the package ‘glue’ and use the glue function to interpolate your variable:

glue("C:\\Folder\\Sub1\\Sub2\\{df}.xpt")

CodePudding user response:

you need the paste0 command.

file = paste0("C:\\Folder\\Sub1\\Sub2\\", df, ".xpt")

Basically, everything inside the brackets will be pasted together. A similar command is paste which will automatically introduce a space between the concatenated strings or whatever you tell it with the sep arguement.

  •  Tags:  
  • r
  • Related