agstudy
agstudy

Reputation: 121568

best method to set rownames or row.names?

Is there any difference between this 3 methods to set row names?

x1 <- data.frame(1)          ## I think this one is faster.why?
attr(x1,"row.names") <- 10L

x2 <- data.frame(1)
row.names(x2) <- 10L

x3 <- data.frame(1)
rownames(x3) <- 10L

Upvotes: 3

Views: 1003

Answers (1)

coanil
coanil

Reputation: 272

(Edited to include Jake Burkhead's solution).

The first one is faster. Don't know why for sure, but presumably because accessing by identifier or by function adds some overhead.

x1 <- data.frame(1)
x2 <- data.frame(1)
x3 <- data.frame(1)
x4 <- data.frame(1)

microbenchmark(
  attr(x1, "row.names") <- 10L,
  structure(x2, row.names = 10L),
  row.names(x3) <- 10L,
  rownames(x4) <- 10L)

This is the result on my machine:

Unit: microseconds
                           expr    min      lq median      uq    max neval
   attr(x1, "row.names") <- 10L  2.625  4.4975  4.795  5.1100  7.257   100
 structure(x2, row.names = 10L) 18.646 25.0555 26.855 27.6205 48.376   100
           row.names(x3) <- 10L 20.517 27.8335 28.795 30.3845 90.025   100
            rownames(x4) <- 10L 22.027 31.0540 31.785 32.9445 55.254   100

Upvotes: 2

Related Questions