通过 R 中的函数传递字符串

Kat*_*tyB 2 r function path

我有以下功能:

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 = "\\"))

}
Run Code Online (Sandbox Code Playgroud)

显然这只是该功能的开始,但我已经遇到了一些问题。在这里,我尝试定义最终希望保存结果的目录。使用该函数的示例是:

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)
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

Error in paste(FigureFolder, "SavedData", sep = "\\") : 
  argument "FigureFolder" is missing, with no default
Run Code Online (Sandbox Code Playgroud)

我猜测是由于函数不知道“FigureFolder”是什么,我的问题是如何通过函数传递这个字符串?

Pau*_*tra 5

因为您不使用命名参数,所以该FigureFolder参数被放入.... 只需使用:

example_Foo(catg, FigureFolder = FigureFolder)
Run Code Online (Sandbox Code Playgroud)

此外:

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 = "\\"))

}
Run Code Online (Sandbox Code Playgroud)

也可以替换为:

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 = "\\"))

}
Run Code Online (Sandbox Code Playgroud)

或者更简单:

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

}
Run Code Online (Sandbox Code Playgroud)

保持代码简单可以使其更易于阅读(也适合您自己)并且更易于使用和维护。