2016-05-13 68 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