本文介绍了R函数没有返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在用他的一些代码帮助我的一个朋友。我不知道如何解释这种奇怪的行为,但我可以告诉他他的功能没有明确地返回任何东西。这是一个最小可重现的例子: derp< - function(arg){ arg data data #[1] 503 derp(500)#输出 class(derp(500))#[1]numeric 解决方案您需要了解函数返回值,然后打印该值。默认情况下,一个函数返回最后一个求值表达式的值,在这个例子中是赋值。 arg (请注意,在R中,赋值是一个表达式, )这就是为什么 data 导致 data 的原因c>包含503。 但是,默认情况下,返回的值不会打印到屏幕上,除非您将函数的最终表达式自行隔离。这是R中的一个怪癖。所以,如果你想看到值: derp< - function(arg) { arg< - arg + 3 arg } 或者只是 derp< - 函数(arg) arg + 3 I was helping a friend of mine with some of his code. I didn't know how to explain the strange behavior, but I could tell him that his functions weren't explicitly returning anything. Here is a minimum reproducible example:derp <- function(arg){ arg <- arg+3}data <- derp(500)data#[1] 503derp(500)#nothing outputsclass(derp(500))#[1] "numeric"Is there a name for this that I can google? Why is this happening? Why isn't arg being destroyed after the call to derp() finishes? 解决方案 You need to understand the difference between a function returning a value, and printing that value. By default, a function returns the value of the last expression evaluated, which in this case is the assignmentarg <- arg + 3(Note that in R, an assignment is an expression that returns a value, in this case the value assigned.) This is why data <- derp(500) results in data containing 503.However, the returned value is not printed to the screen by default, unless you isolate the function's final expression on its own line. This is one of those quirks in R. So if you want to see the value:derp <- function(arg){ arg <- arg + 3 arg}or justderp <- function(arg)arg + 3 这篇关于R函数没有返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 04:37