向量通常是在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