3

In case of assignment (by reference), with = FALSE can be replaced by LHS in parentheses, (). This nice feature does not work when simply subsetting the column without assignment. Of course there is workarount with .SD/.SDcols or get()/mget(), but it would be nice to subset a column just the same way, with or without assignment.

dt  <- data.table(A = 1:3, B = 4:6 )
col  <- "A"
cols  <- c("A","B")

# assign the old way
dt[,  col  :=     9 , with=FALSE]         
dt[,  cols := .(9,8), with=FALSE]

# assign the new way
dt[, (col)  :=     8 ]        
dt[, (cols) := .(8,7)]      

# But the above syntax does not work for subsetting
dt[, (col)]
dt[, (cols)]

# I know how I can subset col and cols, but that is not the question here, 
# e.g.:
dt[,  col,  with=FALSE]
dt[,  cols, with=FALSE]
dt[, .SD, .SDcols=col]
dt[, .SD, .SDcols=cols]

# Below, further (there are even more) types of subsetting but they are not 
# the same for col and cols, which is importent for looping where I dont 
# know how many cols I call in advance.

dt[, get(col)]
dt[, mget(cols)]
dt[[col]] # Returns a vector, nor running: dt[[cols]] 

In other words: if dt[ , (col) := 8] runs, as a naive user I expect df[ , (col)] to run as well. Probably there would be a conflict in [data.table so that cannot be implemented?

Henrik
  • 65,555
  • 14
  • 143
  • 159
rluech
  • 606
  • 4
  • 15
  • 1
    `parents != parentheses` :-) – talat May 23 '16 at 12:40
  • 2
    You can use `dt[[col]]` – akrun May 23 '16 at 12:42
  • http://stackoverflow.com/a/20043412/1412059 – Roland May 23 '16 at 14:14
  • 1
    you forget about the most ninja method `dt[, eval(as.name(col))]` :) – jangorecki May 23 '16 at 17:15
  • @ akrun /Roland /jangorecki These are further ways of subsetting a column via its name in charcters. But they return a vector and only work for a single name, i.e. not working for cols <- c("A","B") directly without looping over cols. It would be intuitive if the syntax stays the same whether we call a column (or multiple) as LHS or as singlular statement. – rluech May 23 '16 at 23:04

0 Answers0