KatyB
KatyB

Reputation: 3990

pass string through a function in R

I have the following function:

example_Foo <- function( ...,FigureFolder){

  # check what variables are passed through the function  
  v_names <- as.list(match.call())
  variable_list <- v_names[2:(length(v_names)-2)] 

  # create file to store figures
  subDir <- c(paste(FigureFolder,"SavedData",sep = "\\"))

}

Obviously this is just the start of the function, but I have already run into some problems. Here, I am trying to define the directory where I eventually want my results to be saved. An example of using the function is:

weight <- c(102,20,30,04,022,01,220,10)
height <- c(102,20,30,04,022,01,220,10)

catg <- c(102,20,30,04,022,01,220,10)
catg <- matrix(height,nrow = 2)

FigureFolder <- "C:\\exampleDat"

# this is the function
example_Foo(catg,FigureFolder)

This generates the following error:

Error in paste(FigureFolder, "SavedData", sep = "\\") : 
  argument "FigureFolder" is missing, with no default

which i'm guessing is due to the function not knowing what 'FigureFolder' is, my question is how do I pass this string through the function?

Upvotes: 2

Views: 9140

Answers (2)

Paul Hiemstra
Paul Hiemstra

Reputation: 60984

Because you do not use a named argument, the FigureFolder argument is put into .... Just use:

example_Foo(catg, FigureFolder = FigureFolder)

In addition:

example_Foo <- function( ...,FigureFolder){

  # check what variables are passed through the function  
  v_names <- as.list(match.call())
  variable_list <- v_names[2:(length(v_names)-2)] 

  # create file to store figures
  subDir <- c(paste(FigureFolder,"SavedData",sep = "\\"))

}

could also be replaced by:

example_Foo <- function( ...,FigureFolder){

  # check what variables are passed through the function  
  variable_list = list(...)

  # create file to store figures
  subDir <- c(paste(FigureFolder,"SavedData",sep = "\\"))

}

Or even simpler:

example_Foo <- function(variable_list, FigureFolder){
  # create file to store figures
  subDir <- c(paste(FigureFolder,"SavedData",sep = "\\"))

}

Keeping your code simple makes it easier to read (also for yourself) and easier to use and maintain.

Upvotes: 5

Yaniv Brandvain
Yaniv Brandvain

Reputation: 113

You need to providea value for FigureFolder, eg

example_Foo(catg,FigureFolder="FigureFolder")

Upvotes: 2

Related Questions