2012-05-31 67 views
1

在R中,打印乘法表的最快方式(最短代碼)是多少? 函數seq rep和綁定函數有所幫助,但我正在尋找最短的代碼行來執行此操作。用最小代碼打印乘法表

rbind("1\'s"=1:12, "2\'s"=seq(2,24,2), "3\'s"=seq(3,36,3), 
     "4\'s"=seq(4,48,4), "5\'s"=seq(5,60,5), "6\'s"=seq(6,72,6)) 

打印1到6的橫向(橫向)。任何人都知道如何以更緊湊的方式執行此操作?

回答

8
tbl <- outer(1:6, 1:12, "*") 
rownames(tbl) <- paste(1:6, "'s", sep="") 
tbl 

您可以通過使用paste0(1:6, "'s")

這似乎略有好轉做出更爲簡潔:

> v<-setNames(1:6, paste0(1:6, "\'s")) 
> v %o% v 
    1's 2's 3's 4's 5's 6's 
1's 1 2 3 4 5 6 
2's 2 4 6 8 10 12 
3's 3 6 9 12 15 18 
4's 4 8 12 16 20 24 
5's 5 10 15 20 25 30 
6's 6 12 18 24 30 36 
+0

快如閃電(進入) 。謝謝。 – VISQL

+1

還剩幾個字符:'v < - 1:6; (tbl < - outer(setNames(v,paste0(v,「's」)),1:12))' –

5

outer(1:6, 1:12, "*")的快捷方式:

> 1:6 %o% 1:12 
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] 
[1,] 1 2 3 4 5 6 7 8 9 10 11 12 
[2,] 2 4 6 8 10 12 14 16 18 20 22 24 
[3,] 3 6 9 12 15 18 21 24 27 30 33 36 
[4,] 4 8 12 16 20 24 28 32 36 40 44 48 
[5,] 5 10 15 20 25 30 35 40 45 50 55 60 
[6,] 6 12 18 24 30 36 42 48 54 60 66 72