R函数没有返回值 [英] R function with no return value

查看:146
本文介绍了R函数没有返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用他的一些代码帮助我的一个朋友。我不知道如何解释这种奇怪的行为,但我可以告诉他他的功能没有明确地返回任何东西。这是一个最小可重现的例子:

  derp<  -  function(arg){
arg < - arg + 3


data < - derp(500)
data
#[1] 503
derp(500)
#输出
class(derp(500))
#[1]numeric



<有没有一个这样的名称,我可以谷歌?这是为什么发生?为什么在调用derp()完成后不会销毁arg?

解决方案

您需要了解函数返回值,然后打印该值。默认情况下,一个函数返回最后一个求值表达式的值,在这个例子中是赋值。

  arg < -  arg + 3 

(请注意,在R中,赋值是一个表达式, )这就是为什么 data <-derp(500)导致 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] 503
derp(500)
#nothing outputs
class(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 assignment

arg <- 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 just

derp <- function(arg)
arg + 3

这篇关于R函数没有返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆