我浏览了这里的论坛,发现<<-
函数内的变量分配给全局变量(可以在函数外部访问(。
我在下面这样做了,但无济于事 - 有什么想法吗?
> 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()
运行良好。
注意:
使用<<-
是一种不好的做法。您可以阅读此线程以了解更多信息。
您需要运行该函数。在这里,你只需定义它。更进一步,在查找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))
附言
即使你想使用return(out)
你仍然需要在定义它之后运行该函数。
此外,使用return()
不会将变量添加到全局变量。你需要在调用函数时分配它,如下所示:
out <- myfun(df)
你可以只使用return(out)
作为函数的最后一行,然后在每次需要访问变量时调用你的函数。