Create a named vector with names stored in a variable
Often I want create a named vector and the names are stored in a variable. I must use a 2 steps function:
names <- paste0("V", 1:100)
A <- 1:100
names(A) <- names
A <- 1:100
names(A) <- names
I search a way to do the same in a single step. Here is the solution:
A <- structure(1:100, .Dim = 100L,
.Dimnames = list(names))
.Dimnames = list(names))
But which one is the faster?
names <- paste0("V", 1:100)
library(microbenchmark)
microbenchmark({
A <- 1:100
names(A) <- names},
{A <- structure(1:100, .Dim = 100L,
.Dimnames = list(names))},
times = 1000L)
Unit: microseconds
expr min lq mean
{ A <- 1:100 names(A) <- names } 1.02 1.068 1.222658
{ A <- structure(1:100, .Dim = 100L, .Dimnames = list(names)) } 5.78 6.295 6.486045
median uq max neval cld
1.2475 1.3310 4.658 1000 a
6.4090 6.5575 33.790 1000 b
library(microbenchmark)
microbenchmark({
A <- 1:100
names(A) <- names},
{A <- structure(1:100, .Dim = 100L,
.Dimnames = list(names))},
times = 1000L)
Unit: microseconds
expr min lq mean
{ A <- 1:100 names(A) <- names } 1.02 1.068 1.222658
{ A <- structure(1:100, .Dim = 100L, .Dimnames = list(names)) } 5.78 6.295 6.486045
median uq max neval cld
1.2475 1.3310 4.658 1000 a
6.4090 6.5575 33.790 1000 b
In conclusion, the 2-steps function is 6 times faster than the 1-step function. It was not intuitive !
Commentaires
Enregistrer un commentaire