R function not returning values

我们两清 提交于 2019-11-27 05:37:28

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.

You simply need to evaluate the object at the end of your function so it will return a value. See the simple example below:

funA <- function(x) {
    a <- x
}

funB <- function(x) {
    b <- x
    b
}

funA(1) # prints nothing
funB(1) # prints 'b'
[1] 1

EDIT:

As @MrFlick points out, both funA and funB return the evaluation of the last expression, but funA will not print anything. However, if you assign the output of funA(1) an object, that object will produce the value 1:

z <- funA(1)
z
[1] 1
z == funB(1)
[1] TRUE

The moral of the story is that you either need to assign the output of IMDBmovierating to an object, or explicitly evaluate df at the end of the function.

Looks like you just had a few typos.

Try this and dont forget to include your library to help people out when answering you. :)

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

test <- IMDBmovierating(1984)
test
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!