How to create a vector with names of its elements in one line code in R?
-
12-09-2020 - |
Question
How to create a vector with names of its elements in one line code in R?
Vectors are frequently created in R but most of the times we don’t give names to their elements and if we want to give their names then we can use setNames function. This function will help us to name the vector elements in a single line of code, obviously this will save our time and workspace in R.
Example
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
Advertisements
Not affiliated with Tutorialspoint