2013-12-20 61 views
1

我想将变量传递给一个函数,并将它们用作列表,并且我有一个函数用“=”分割字符向量的项,并且将它们放入列表中。创建一个列表,从一个字符向量提供给一个函数

my.function <- function(x) { 
    args <- x 
    newl <- list() 

for (i in 1:length(args)) { 
    keyval <- strsplit(args[[i]],"=")[[1]]; 
    key <- keyval[1]; val <- keyval[2]; 
    newl[[ key ]] <- val; 
} 
return(newl) 
} 

char<- c("name=value_1", "title=title", "show=show") 

my.function(char) 

$name 
[1] "value_1" 

$title 
[1] "title" 

$show 
[1] "show" 

然后我可以使用函数内这些参数只是这样做:

args[['title']] 

但我当包含在这样的字符等号它工作正常,当然想将变量传递给函数,而不仅仅是字符。所以,我想的功能能够工作当我这样做:

value_1 = "A" 
show= TRUE 
title= paste("This is my title for ", value_1, sep="") 

my.function(name=value_1, title=title, show=show) 

我可以只粘贴值是这样的:

char= c(paste("name=", value_1, sep=""), 
     paste("title=", title, sep=""), 
     paste("show=", show, sep="")) 

但我不知道是否有更好的方法将这些变量作为参数传递给函数。感谢您的帮助!

回答

2

您可以使用...

my.function <- function(...) list(...) 

此功能只创建一个基于ussed参数列表。

value_1 <- "A" 
show <- TRUE 
title <- paste("This is my title for ", value_1, sep="") 


my.function(name = value_1, title = title, show = show) 
$name 
[1] "A" 

$title 
[1] "This is my title for A" 

$show 
[1] TRUE 

此功能基于函数调用的参数的特征向量:

my.function <- function(...) { 
    argList <- list(...) 
    res <- paste(names(argList), unlist(argList), sep = "=") 
    return(res)  
} 

my.function(name=value_1, title=title, show=show) 
[1] "name=A"      "title=This is my title for A" "show=TRUE" 

此功能类似于您的一个。它说明了如何访问函数调用的参数:

my.function <- function(...) { 
    argList <- list(...) 
    newl <- list() 
    for (i in seq_along(argList)) { 
    key <- names(argList)[i] 
    val <- argList[[i]] 
    newl[[key]] <- val 
    } 
    return(newl)  
} 

my.function(name = value_1, title = title, show = show) 
$name 
[1] "A" 

$title 
[1] "This is my title for A" 

$show 
[1] TRUE 
+0

谢谢斯文...如果我想使用它在我具备的功能,它告诉我它无法找到x如果我调整我的功能像这样:my.function < - function(...){ args < - x; newl < - list();对于(i in 1:length(args)){ keyval < - strsplit(args [[i]],“=”)[[1]]; key < - keyval [1]; val < - keyval [2]; newl [[key]] < - val; } return(newl) } – user2337032

+0

@ user2337032您的最终目标是什么?你想要什么函数返回? –

+0

我希望能够给变量作为参数给我有同样的功能(虽然它看起来很简单,只是转换为列表我使它更简单的帖子...) – user2337032