The following code block taken from chernan's sample REST queries will apply FUN to a list of parameters, but "param_name" is not provided. How is this possible?
rcurl_request <- function(service_url, parameters) {
# Collapse all parameters into one string
all_parameters <- paste(
sapply(names(parameters),
FUN=function(param_name, parameters) {
paste(param_name, paste(parameters[[param_name]], collapse=','), collapse='', sep='=')
},
parameters),
collapse="&")
# Paste base URL and parameters
requested_url <- paste0(service_url, all_parameters)
# Encode URL (in case there would be any space character for instance)
requested_url <- URLencode(requested_url)
# Start request to service
response <- getURL(requested_url, .opts = list(ssl.verifypeer = FALSE))
return(response)
}
Run Code Online (Sandbox Code Playgroud)
该*apply系列函数被设计为适用FUN于提供给各自的对象的元素*apply的功能。
在你的例子中,向其中元件FUN被施加是个别的元件names(parameters)。sapply()获取第一个元素,names(parameters)[1]并将其传递给FUN作为第一个参数。因此param_name用于指代names(parameters)[1],然后指代names(parameters)[2],依此类推。
换句话说,sapply()安排依次传递sapply()s 第一个参数的元素以FUN提供这些元素作为 的第一个参数FUN。
通过这个更简单的示例,您可以更清楚地看到这一点:
sapply(1:10, FUN = function(i) {writeLines(paste("working on", i)); i})
Run Code Online (Sandbox Code Playgroud)
因此i依次取值 1、2、...、10,并且匿名函数对它们中的每一个起作用:
> sapply(1:10, FUN = function(i) {writeLines(paste("working on", i)); i})
working on 1
working on 2
working on 3
working on 4
working on 5
working on 6
working on 7
working on 8
working on 9
working on 10
[1] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)