lizzie
lizzie

Reputation: 606

How can I return a result and a written statement from a function?

I want this function to return both the result (number) and the text.

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" ,
      )
}

Doing the above only returns the number of the result.

Desired output:

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

Upvotes: 0

Views: 79

Answers (3)

Marcel
Marcel

Reputation: 2794

Here is a simpler solution with 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)))
}

and the result looks like:

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

Upvotes: -1

IRTFM
IRTFM

Reputation: 263301

It's possible that these other folks have the same confusion as do you and that you will be happy with their advice, but to actually return multiple items of dissimilar class (which is what you asked) you do need a single list (of possibly complex structure).

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"

Upvotes: 3

Gopala
Gopala

Reputation: 10473

Modify the function to do this instead?

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))
}

Upvotes: 2

Related Questions