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

がcat' – Gabe

+1

使用リスト ''後return'文を置きます。.. .... –

+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

出力デバイスに置かない限り、それはそれを表す文字ベクトルです。あなたはそれをとって 'cat'を取ると、関数が正しいことをするのを見るでしょう。 – 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 
関連する問題