Skip to content
Prev 43891 / 63424 Next

Quiz: How to get a "named column" from a data frame

This isn't super-concise, but has the virtue of being clear:

nv <- c(a=1, d=17, e=101)
df <- as.data.frame(cbind(VAR = nv))

identical(nv, setNames(df$VAR, rownames(df)))
# TRUE


It seems to be more efficient than the other methods as well:

f1 <- function() setNames(df$VAR, rownames(df))
f2 <- function() t(df)[1,]
f3 <- function() as.matrix(df)[,1]

r <- microbenchmark(f1(), f2(), f3(), times=1000)
r
# Unit: microseconds
#   expr    min      lq median      uq      max
# 1 f1() 14.589 17.0315 18.608 19.3220   89.388
# 2 f2() 68.057 70.8735 72.240 75.8065 3707.012
# 3 f3() 58.153 61.2600 62.521 65.0380  238.483

-Winston



On Sat, Aug 18, 2012 at 10:03 AM, Martin Maechler
<maechler at stat.math.ethz.ch> wrote: