< - 不工作 - R - 从外部函数调用对象

时间:2017-08-15 22:10:41

标签: r function dplyr global-variables

我查看了这里的论坛并找出<<-将函数内部的变量赋值给全局变量(可以在函数外部访问)。

我在下面这样做了,但无济于事 - 有什么想法吗?

> Billeddata_import <- function(burl="C:\\Users\\mcantwell\\Desktop\\Projects\\M & V Analysis\\Final_Bills.csv"){
+         billeddata<-read.csv(burl,header=TRUE, sep=",",stringsAsFactors = FALSE) %>%
+             mutate(Usage=as.numeric(Usage)) %>%
+                 #Service.Begin.Date=as.Date(Service.Begin.Date,format='%m/%d/%Y'),
+                  #Service.End.Date=as.Date(Service.End.Date,format='%m/%d/%Y')) %>%
+        
+         filter(UOM=="Kw",
+                !is.na(Usage),
+                Service.Description %in% c("Demand","Demand On Peak", "Demand Off Peak", "Dmd Partial Pk")) %>%
+         group_by(Location..,Service.Begin.Date,Service.End.Date) %>%
+         summarise(monthly_peak=max(Usage))
+         out<<-billdata
+     }
> out
Error: object 'out' not found
> 

对象billdata是我在Billeddata_import()中清理的数据表,我希望在以后的函数中使用它。

单独运行该函数会产生:

> Billeddata_import()
Error in Billeddata_import() : object 'billdata' not found

没有out<<-billdata行,Billeddata_import()运行正常。

2 个答案:

答案 0 :(得分:2)

您可以使用return(out)作为函数的最后一行,然后在每次需要访问变量时调用函数。

答案 1 :(得分:2)

注意: 使用<<-是不好的做法。您可以阅读 thread 以了解更多信息。

您需要运行该功能。在这里,您只需定义它。更进一步并在查找out之前运行它。

由于我们没有您的数据,请查看以下示例;

#This is an example:
myfun <- function(xdat=df) {
  billeddata <- xdat %>% select(-var3) %>% 
                        filter(var1=="treatment5")

  out<<-billeddata
  }

 myfun(df) #You need to run the function!!!
 out

#         var1    var2       value 
# 1 treatment5 group_2 0.005349631 
# 2 treatment5 group_2 0.005349631 
# 3 treatment5 group_1 0.005349631

<强> 数据:

df <- structure(list(var1 = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 
      3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("treatment1", "treatment2", 
      "treatment3", "treatment4", "treatment5"), class = "factor"), 
      var2 = structure(c(1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 
      2L, 2L, 1L, 1L, 1L), .Label = c("group_1", "group_2"), class = "factor"), 
      var3 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 3L, 2L, 2L, 3L, 
      2L, 3L, 2L, 2L, 3L), .Label = c("C8.0", "C8.1", "C8.2"), class = "factor"), 
      value = c(0.010056478, 0.009382918, 0.003014983, 0.005349631, 
      0.005349631, 0.010056478, 0.009382918, 0.003014983, 0.005349631, 
      0.005349631, 0.010056478, 0.009382918, 0.003014983, 0.005349631, 
      0.005349631)), .Names = c("var1", "var2", "var3", "value"
  ), class = "data.frame", row.names = c(NA, -15L))

<强> P.S。

即使您想使用return(out),您仍需要在定义后运行该功能。

此外,使用return()不会向您的全局添加变量。您需要在调用函数时分配它,如下所示:

out <- myfun(df)
相关问题