我创建了函数mad_libs
,其中将省略号作为参数传递并解压缩。功能“有效”,因为它打印并且显然没有任何问题,但我没有得到我通过的论据。
功能如下:
mad_libs <- function(...){
args <- list(...)
place <- args[["place"]]
adjective <- args[["adjective"]]
noun <- args[["noun"]]
paste("News from", place, "today where", adjective, "students took
to the streets in protest of the new", noun, "being installed on campus.")
}
假设我通过mad_libs("NIFLHEIM", "possessed", "fountain")
或其他任何参数,总是在“”之间,我得到:
[1] "News from today where students took to the streets in protest
of the new being installed on campus."
不打印参数。
我遇到了打印问题,因为我的操作系统是用葡萄牙语编写的,但似乎拼写规则不是问题。
在RStudio上运行R 3.3.1,使用巴西葡萄牙语运行Windows 10。
答案 0 :(得分:3)
你应该学习argument matching。
如果您希望位置匹配和名称匹配都有效,可以像这样使用do.call
:
mad_libs <- function(...){
args <- list(...)
fun <- function(place, adjective, noun)
paste("News from", place, "today where", adjective, "students took to the streets in protest of the new", noun, "being installed on campus.")
do.call(fun, args)
}
mad_libs("NIFLHEIM", "possessed", "fountain")
#[1] "News from NIFLHEIM today where possessed students took to the streets in protest of the new fountain being installed on campus."
mad_libs(adjective = "possessed", "NIFLHEIM", "fountain")
#[1] "News from NIFLHEIM today where possessed students took to the streets in protest of the new fountain being installed on campus."
当然,如果没有令人信服的理由来创建args
,您可以简单地传递省略号:
mad_libs <- function(...){
fun <- function(place, adjective, noun)
paste("News from", place, "today where", adjective, "students took to the streets in protest of the new", noun, "being installed on campus.")
fun(...)
}