如何从函数返回结果和书面声明?

时间:2016-05-13 00:45:17

标签: r function

我希望此函数返回结果(数字)和文本。

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  return(list(sq, cube))
  cat("The sum of squares is", sq, "\n" ,
      "The sum of cubes is", cube, "\n" ,
      )
}

执行上述操作仅返回结果编号。

期望的输出:

sum_of_squares_cubes(2,3)
13
35
"The sum of squares is 13"
"The sum of cubes is 35"

3 个答案:

答案 0 :(得分:3)

这些其他人可能会像你一样有同样的困惑,并且你会对他们的建议感到满意,但实际上返回多个不同类的项目(这是什么你问)你确实需要一个单个列表(可能是复杂的结构)。

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  return(list(sq, cube,  sqmsg=paste("The sum of squares is", sq, "\n") , 
                         cubemsg= paste("The sum of cubes is", cube, "\n") 
       )) 
   }

> sum_of_squares_cubes(2,4)
[[1]]
[1] 20

[[2]]
[1] 72

$sqmsg
[1] "The sum of squares is 20 \n"

$cubemsg
[1] "The sum of cubes is 72 \n"

答案 1 :(得分:2)

修改函数来代替吗?

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text <- paste("The sum of squares is ", sq, "\n",
                "The sum of cubes is ", cube, "\n", sep = '')
  return(list(sq, cube, text))
}

答案 2 :(得分:-1)

这是一个更简单的sprintf解决方案:

sum_of_squares_cubes <- function(x,y) {
  sq = x^2 + y^2
  cube = x^3 + y^3
  text1 <- sprintf("The sum of squares is %d", sq)
  text2 <- sprintf("and the sum of cubes is %d",  cube)
  return(cat(c("\n", sq, "\n", cube, "\n", text1, "\n", text2)))
}

,结果如下:

 13 
 35 
 The sum of squares is 13 
 and the sum of cubes is 35