如何在 R 的一行程式碼中建立帶有其元素名稱的向量?


我們在 R 中經常建立向量,但很多時候我們不會對它們的元素命名,如果我們想要給它們命名,可以使用 setNames 函式。此函式將幫助我們在單行程式碼中給向量元素命名,這顯然會節省我們在 R 中的時間和工作空間。

示例

s
> V1 <- setNames(c(1:10), LETTERS[1:10])
> V1
A B C D E F G H I J
1 2 3 4 5 6 7 8 9 10
> V2 <- setNames(rep(c(1:5),2), LETTERS[1:10])
> V2
A B C D E F G H I J
1 2 3 4 5 1 2 3 4 5
> V3 <- setNames(rep(c(1:5),2), rep(LETTERS[1:5],2))
> V3
A B C D E A B C D E
1 2 3 4 5 1 2 3 4 5
> V4 <- setNames(rep(c(1:5),each=2), rep(LETTERS[1:5],2))
> V4
A B C D E A B C D E
1 1 2 2 3 3 4 4 5 5
> V5 <- setNames(rep(c(1:5),each=2), LETTERS[1:10])
> V5
A B C D E F G H I J
1 1 2 2 3 3 4 4 5 5
> V6 <- setNames(rep(c(1:5),each=2), rep(LETTERS[1:5],each=2))
> V6
A A B B C C D D E E
1 1 2 2 3 3 4 4 5 5
> V7 <- setNames(sample(1:100,10), rep(LETTERS[1:5],each=2))
> V7
 A  A B  B  C  C  D  D  E  E
55 63 8 33 54 43 38 40 16 45
> V8 <- setNames(sample(1:100,10), rep(LETTERS[1:5],times=2))
> V8
 A B  C D  E  A  B C  D  E
80 6 83 9 72 45 99 2 82 67
> V9 <- setNames(sample(1:100,10), LETTERS[1:10])
> V9
A B  C  D  E  F  G  H  I J
3 1 87 48 41 45 79 33 18 8
> V10 <- setNames(sample(1:500,10), LETTERS[10:1])
> V10
  J   I   H  G   F   E   D   C   B   A
164 493 350 37 226 149 374 205 327 242
> V11 <- setNames(sample(1:500,5), c("S1","S2","S3","S4","S5"))
> V11
 S1 S2 S3  S4  S5
452 9 106 175 306
> V12 <- setNames(sample(1:50,5), c("Age1","Age2","Age3","Age4","Age5"))
> V12
Age1 Age2 Age3 Age4 Age5
6 32 15 13 35

更新於:2020-08-12

763 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.