user4338
user4338

Reputation: 173

How to select a column of a data.table via a variable

I've got a data table, and instead of addressing a particular column (say column "x") by (a hardcoded) "dt$x", I'd like to get this done in a dynamic manner by facilitating a variable instead, ie. "dt${var}".

I've already tried "dt[, eval(quote(var)), with=FALSE)", as well as "dt[, c(var), with=FALSE)", but unfortunately that's not working in my particular case at hand.

What I'm trying to achieve is opening up a text connection to dynamically selected column of a data.table.

Working

dt_txt_con <- textConnection(as.character(DT$x))
dt_txt <- data.table(read.table(dt_txt_con, sep=","))
close(dt_txt_con)

Not working

#dt_txt_con <- textConnection(as.character(as.list(DT[,c(var), with=FALSE])))
dt_txt_con <- textConnection(as.character(DT[, eval(quote(var)), with=FALSE]))
dt_txt <- data.table(read.table(dt_txt_con, sep=","))
close(dt_txt_con)

Resulting in an error message

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  line 1 did not have 38 elements

How best to tackle this one?

-Sil68

EDIT

Sample data (excerpt from a hugh data table held in memory, no file)

DT <- data.table(
            "age,sex,geo\\time" = c("TOTAL,F,AD", "TOTAL,F,AL", "TOTAL,F,AM", "TOTAL,F,AT", "TOTAL,F,AZ"),
            "2014" = c(NA,    NA,      NA,      4351253, NA),
            "2013" = c(37408, NA,      NA,      4328238, 4707690),
            "2012" = c(38252, NA,      1684000, 4309977, 4651601),
            "2011" = c(38252, 1409931, 1679066, 4296293, 4594023),
            "2010" = c(40296, NA,      1673656, 4285442, 4542083)
        )

Variable

var <- "age,sex,geo\\time"

Upvotes: 1

Views: 131

Answers (1)

user4338
user4338

Reputation: 173

As indicated by David,

dt_txt_con <- textConnection(as.character(DT[, .SD[[var]]]))

is working like a charm.

Upvotes: 1

Related Questions