![](/img/trans.png)
[英]How can i set a "key" argument in a gather function using a variable?
[英]How can I set a conditional function argument value here?
我想基于另一个参数的值自动在函数中设置参数的值。
更具体地说,我想设置一个时区值( offset
)以自动调整给定region
时间值。
但是,我的实现似乎不起作用(因为偏移量永远不会应用,除非我专门将它作为参数传递给函数)。
该函数的一部分(应该)根据region
的值设置offset
值,并且还连接到相应的Elasticsearch服务器。
这就是我所拥有的:
if (region == "EU") {
offset = "+00:00:00"
# Code to connect to EU ElasticSearch server
} else if (region == "US") {
offset = "-06:00:00"
# Code to connect to US ElasticSearch server
} else {
paste0(stop("Incorrect region supplied: ", region))
}
功能:
time_function <- function(region, retailer, start_date, end_date, offset = "+00:00:00"){
# Function body
}
(请注意,我已将offset
的默认值设置为"+00"
,否则它将抛出错误的参数缺失。)
显然,我在某个地方出错了,因为除非我在参数列表中明确指定,否则永远不会应用偏移量。
这就是我想做的:
如果region == "US"
,则将offset
设置为"-06:00:00"
,否则,如果region == "EU"
,则将offset
设置为"+00:00:00"
Else Error message: "supply valid region"
简而言之,我希望设置一个条件参数值。
我该如何实现?
您的代码正常工作。
> time_function <- function(region){
+ # Function body
+ if (region == "EU") {
+ offset = "+00:00:00"
+ # Code to connect to EU ElasticSearch server
+ } else if (region == "US") {
+ offset = "-06:00:00"
+ # Code to connect to US ElasticSearch server
+ } else {
+ stop(paste0("Incorrect region supplied: ", region))
+ }
+
+ return(offset)
+ }
>
> time_function("EU")
[1] "+00:00:00"
> time_function("US")
[1] "-06:00:00"
> time_function("CH")
Error in time_function("CH") : Incorrect region supplied: CH
要优化代码,可以使用开关。
> time_function <- function(region){
+ # Function body
+ offset <- switch(region,
+ EU = "+00:00:00",
+ US = "-06:00:00",
+ stop(paste0("Incorrect region supplied: ", region)))
+
+ return(offset)
+ }
>
> time_function("EU")
[1] "+00:00:00"
> time_function("US")
[1] "-06:00:00"
> time_function("CH")
Error in time_function("CH") : Incorrect region supplied: CH
有两个参数:
> time_function <- function(region){
+ # Function body
+ list2env(switch(region,
+ EU = list(offset = "+00:00:00", con = "EU_con"),
+ US = list(offset = "+00:00:00", con = "US_con"),
+ stop(paste0("Incorrect region supplied: ", region))), envir = environment())
+
+ return(c(offset, con))
+ }
>
> time_function("EU")
[1] "+00:00:00" "EU_con"
> time_function("US")
[1] "+00:00:00" "US_con"
> time_function("CH")
Error in list2env(switch(region, EU = list(offset = "+00:00:00", con = "EU_con"), :
Incorrect region supplied: CH
事实证明,我已经按照分配执行的顺序进行了监督,并且刚刚发现了它。
对于那些可能遇到类似问题的人,可能值得强调一下我做错了什么:我在使用offset
值后设置了offset
值,这意味着使用/处理了offset
值(使用上一次迭代的值),然后为其分配了新值。值。
简而言之,我的实现是完全正确的,但是事件的顺序是不正确的 。
因此,请确保在处理所需的值之前先进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.