2016-05-13 72 views
0

我想这个函数返回结果(数字)和文本。如何从函数返回结果和书面声明?

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" 
+0

把'return'声明cat' – Gabe

+1

使用列表后'.. ... –

+2

'return()'后面没有执行代码。如果您想要打印,请放上'cat()'。 – HubertL

回答

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

输出差不多。只是最后一部分很奇怪。 '“正方形之和为13 \ n立方体之和为35 \ n”' – lizzie

+1

除非您将其放置在某个输出设备上,那就是该字符的矢量表示形式。你把它和'猫',你会看到功能做正确的事情。 – Gopala

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" 
+0

这里缺少一些东西。我收到一个错误。 – lizzie

+2

哦,你想测试代码?这将花费额外的费用。 –

+0

这是正确的方法,只是增加了你不应该使用'cat()'来返回结果,因为你需要重新运行函数来获得结果。 – zacdav

-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