如何在此处设置条件函数参数值?

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" 否则 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 值,这意味着它是 used/processed(使用前一次迭代的值),然后为它分配新值。

简而言之,我的实现是完全正确的,但是事件的顺序不正确

因此,请确保在处理之前设置所需的值。