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

问题描述

很长时间的读者,第一次提问。编写第一个R函数。

  IMDBmovierating<  -  function(movie){
link< - paste(http ://www.omdbapi.com/?t =,movie,& y =& plot = short& r = json,`sep =)`
jsonData< - fromJSON(link )
df< - data.frame(jsonData)
}

然后没有任何反应怀疑它与需要回报有关。不知道我会如何写这个。 返回(df):

  IMDBmovierating<  -  function(movie){
link < - paste(http://www.omdbapi.com/?t=,movie,& y =& plot = short& r = json,sep =)
jsonData< ; - fromJSON(link)
df< - data.frame(jsonData)
return(df)
}

或者,在这种情况下更简单,省略最后的赋值:

  IMDBmovierating <  -  function(movie){
link< - paste(http://www.omdbapi.com/?t=,movie,& y =& plot = short& r = json ,sep =)
jsonData< - fromJSON(link)
data.frame(jsonData)
}

如果最后一个表达式的计算结果是一个结果对象,如 data.frame(..)所做的那样,封闭表达式的返回对象和显式的 return 语句可以省略。



edit:并删除 sep 和关闭括号之后的反标记



edit2:当然MrFlick的评论是正确的:你的代码唯一真正错误的地方就是在网站上可能只是一个错字。即使是赋值也会将分配的值作为结果对象生成,但它是不可见的。因此,您可以分配它,但它不会自动打印在控制台上。

Long time reader, first time asker. Writing first R function.

IMDBmovierating <- function(movie){
  link <- paste("http://www.omdbapi.com/?t=", movie, "&y=&plot=short&r=json", `sep = "")`
  jsonData <- fromJSON(link)
  df <- data.frame(jsonData)
}

And then nothing happens. Suspect it has something to do with return being needed. Not sure how I would write this.

解决方案

To return df, simply write return(df):

IMDBmovierating <- function(movie){
  link <- paste("http://www.omdbapi.com/?t=", movie, "&y=&plot=short&r=json", sep = "")
  jsonData <- fromJSON(link)
  df <- data.frame(jsonData)
  return(df)
}

or, even simpler in this case, omit the last assignment:

IMDBmovierating <- function(movie){
  link <- paste("http://www.omdbapi.com/?t=", movie, "&y=&plot=short&r=json", sep = "")
  jsonData <- fromJSON(link)
  data.frame(jsonData)
}

If the last expression evaluates to a result object, as data.frame(..) does, then this gets the return object of the enclosing expression and the explicit return statement may be omitted.

edit: and remove the back-ticks before sep and after you closing parenthesis

edit2: Of course MrFlick's comment is correct: the only thing really wrong with your code are the back-ticks that probably are simply a typo here on the site. Even the assignment produces the assigned value as a result object, but it is invisible. Hence, you can assign it, but it is not automatically printed on the console.

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

08-18 13:43