Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

r - Print a multiplication table with minimal code

In R, what is the fastest way(shortest code) to print multiplication table? The functions seq rep and the bind functions help, but I'm looking for the shortest line(s) of code to do this.

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

Prints the 1's through 6's going across (horizontally). Anyone know how to perform this in a more compact way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
tbl <- outer(1:6, 1:12, "*")
rownames(tbl) <- paste(1:6, "'s", sep="")
tbl

You could make slightly more compact by using paste0(1:6, "'s")

This seems a slight improvement:

> 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...