标签:
杂谈 |
《R数据可视化手册》第39页里的一段代码,表示对tophit中的lg与avg进行排序,如下所示:
nameorder <- tophit$name[order(tophit$lg,tophit$avg)],对其中的order()用法不太理解,在此理解一下。
tophit中的部分数据如下:
表格 1部分原始数据
No |
name |
lg |
avg |
1 |
Larry Walker |
NL |
0.3501 |
2 |
Ichiro Suzuki |
AL |
0.3497 |
3 |
Jason Giambi |
AL |
0.3423 |
4 |
Roberto Alomar |
AL |
0.3357 |
5 |
Todd Helton |
NL |
0.3356 |
6 |
Moises Alou |
NL |
0.3314 |
7 |
Lance Berkman |
NL |
0.331 |
8 |
Bret Boone |
AL |
0.3307 |
9 |
Frank Catalanotto |
AL |
0.3305 |
10 |
Chipper Jones |
NL |
0.3304 |
11 |
Albert Pujols |
NL |
0.3288 |
12 |
Barry Bonds |
NL |
0.3277 |
13 |
Sammy Sosa |
NL |
0.3276 |
14 |
Juan Pierre |
NL |
0.3274 |
15 |
Juan Gonzalez |
AL |
0.3252 |
16 |
Luis Gonzalez |
NL |
0.3251 |
17 |
Rich Aurilia |
NL |
0.3239 |
18 |
Paul Lo Duca |
NL |
0.3196 |
19 |
Jose Vidro |
NL |
0.3189 |
20 |
Alex Rodriguez |
AL |
0.318 |
21 |
Cliff Floyd |
NL |
0.3171 |
22 |
Shannon Stewart |
AL |
0.3156 |
23 |
Jeff Cirillo |
NL |
0.3125 |
24 |
Jeff Conine |
AL |
0.3111 |
25 |
Derek Jeter |
AL |
0.3111 |
order(tophit$lg,tophit$avg)的意思就是,对tophit中的name进行排序,其中以"lg"与"avg"为关键词。原理与Excel中的排序一样,即以"lg"为主要关键词,以"avg"为次要关键词(Excel中以升序进行排序),排序结果如下所示。nameorder在R语言中的排序结果如下所示,与Excel中的结果一致(R语言中默认为升序排列)。
表格 2Excel与R中的排序结果
No |
name |
lg |
avg |
R语言排序结果: |
24 |
Jeff Conine |
AL |
0.3111 |
Jeff Conine |
25 |
Derek Jeter |
AL |
0.3111 |
Derek Jeter |
22 |
Shannon Stewart |
AL |
0.3156 |
Shannon Stewart |
20 |
Alex Rodriguez |
AL |
0.318 |
Alex Rodriguez |
15 |
Juan Gonzalez |
AL |
0.3252 |
Juan Gonzalez |
9 |
Frank Catalanotto |
AL |
0.3305 |
Frank Catalanotto |
8 |
Bret Boone |
AL |
0.3307 |
Bret Boone |
4 |
Roberto Alomar |
AL |
0.3357 |
Roberto Alomar |
3 |
Jason Giambi |
AL |
0.3423 |
Jason Giambi |
2 |
Ichiro Suzuki |
AL |
0.3497 |
Ichiro Suzuki |
23 |
Jeff Cirillo |
NL |
0.3125 |
Jeff Cirillo |
21 |
Cliff Floyd |
NL |
0.3171 |
Cliff Floyd |
19 |
Jose Vidro |
NL |
0.3189 |
Jose Vidro |
18 |
Paul Lo Duca |
NL |
0.3196 |
Paul Lo Duca |
17 |
Rich Aurilia |
NL |
0.3239 |
Rich Aurilia |
16 |
Luis Gonzalez |
NL |
0.3251 |
Luis Gonzalez |
14 |
Juan Pierre |
NL |
0.3274 |
Juan Pierre |
13 |
Sammy Sosa |
NL |
0.3276 |
Sammy Sosa |
12 |
Barry Bonds |
NL |
0.3277 |
Barry Bonds |
11 |
Albert Pujols |
NL |
0.3288 |
Albert Pujols |
10 |
Chipper Jones |
NL |
0.3304 |
Chipper Jones |
7 |
Lance Berkman |
NL |
0.331 |
Lance Berkman |
6 |
Moises Alou |
NL |
0.3314 |
Moises Alou |
5 |
Todd Helton |
NL |
0.3356 |
Todd Helton |
1 |
Larry Walker |
NL |
0.3501 |
Larry Walker |