[英]Returning and accessing objects from functions in R
I wrote a function in R that returns a list composed of two variables. 我在R中编写了一个函数,该函数返回由两个变量组成的列表。 The function works correctly in that the correct values are returned.
该函数正常工作,因为返回了正确的值。 The problem, however, is that I can't then access the list for further processing.
但是,问题在于我无法访问列表进行进一步处理。 The code is this:
代码是这样的:
grinder <- function(x) {
if(x == "BID") {
miles <- 18.4 * n.row
tolls <- 1.8 * n.row
} else if(x == "SPR") {
miles <- 10.8 * n.row
tolls <- 0
} else if (x == "BRI") {
miles <- 3.8 * n.row
tolls <- 0
} else if (x == "GOO") {
miles <- 66.2 * n.row
tolls <- 1.8 * n.row
} else if (x == "MIL") {
miles <- 108
tolls <- 0
} else if (x == "SMH") {
miles <- 94.6 * n.row
tolls <- 2 * n.row
}
mil.tol <- list(miles,tolls)
return(mil.tol)
}
grinder(x)
The correct values are returned, but I can't then access mil.tol to do anything with those values. 返回了正确的值,但随后我无法访问mil.tol对这些值执行任何操作。 Nor can I get correct values for miles or tolls.
我也无法获得正确的里程或通行费值。 The console returns this:
控制台返回以下内容:
> mil.tol
Error: object 'mil.tol' not found
> miles
Any suggestions? 有什么建议么?
miles
, tolls
and mil.tol
are all local to the function and are not returned, but you can assign the output of the function (ie from the return()
) like below to mil.tol: miles
, tolls
和mil.tol
都是本地的功能,并且不退还,但你可以(从IE分配函数的输出return()
如下面mil.tol:
mil.tol <- grinder(x)
Would recommend also reading this SO post here 建议您在这里阅读这篇SO文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.