【发布时间】:2020-10-19 19:59:01
【问题描述】:
我定义了四个函数。当我调用 ls() 时,我已经执行了所有四个出现在全局环境中的代码。 前两个在第三个内部使用,这可以按预期工作。但是,当我从第四个函数调用第三个函数时,我收到一条错误消息,告诉我 curent_month 不存在。 (我从第四个函数中删除了所有代码,因为失败发生在第一个语句中,所以其余的不相关。) 我一直明白,在全局环境中定义的任何对象都可用于任何子环境(即在函数内部)。 谁能指出我正确的方向?
## Function returns the most recent month having billing revenues
current_month_POSIX <- function(x){
## Fetch current month name for use in label below
current_month_POSIX <- x %>%
filter(Year == 2020) %>%
filter(!is.na(Billing)) %>%
select(Month) %>%
unique()%>%
arrange() %>%
tail(1) %>%
unlist() %>%
as_datetime()
return(current_month_POSIX)
}
current_month_name <- function(x){
current_month_name <- x %>%
filter(Year == 2020) %>%
filter(!is.na(Billing)) %>%
select(Month, month_name) %>%
unique()%>%
arrange() %>%
tail(1) %>%
select(month_name) %>%
substr(.,1,3)
return(current_month_name)
}
curent_month <- function(x){
POSIX <- current_month_POSIX(x)
name <- current_month_name(x)
return(list("current_month_name" = name, "current_month_POSIX" = POSIX))
}
### Function to reduce source data to clustered bar chart table
clustered_bar_data <- function(x){
latest_month <- current_month(x)
}
【问题讨论】:
-
好吧,看起来它应该可以使用正确的输入。您可以通过提供一些应该使用的示例数据来使您的问题可重现吗?如果没有任何东西可以测试它,我们真的无法帮助调试......
-
将每个函数的返回值调用与函数名相同是一种不寻常的风格选择。很难判断问题出在哪里。也许当你调用函数 #4 时,函数 #4 出错,因为它找不到函数
current_month_name(),或者可能current_month_name()被调用但它在定义其同名对象时遇到了问题,问题是current_month_name函数在尝试return(current_month_name)时找不到对象current_month_name。没有东西可以测试,但您可能会考虑重命名以清楚起见 -
许多风格指南建议将函数动词作为名称,这会建议将函数重命名为,例如,
get_current_month_name。 -
我正在取得一些进展。我明天更新。
标签: r function environment