[datatable-help] add a column specifying new column name via a variable

Chris Neff caneff at gmail.com
Wed Jul 25 23:25:28 CEST 2012


Hmmm I would have liked to see

set(dt, j=new_col_name, value=NA)

work but that doesn't. Any reason why necessarily?

On Wed, Jul 25, 2012 at 2:03 PM, Kaupas, George
<George.Kaupas at spansion.com> wrote:
> I'm trying to add empty columns to data.tables using a variable containing the name of the desired column, but I'm unable to figure out how to dereference the variable value to satisfy the := operator.
>
> Here's a simple example:
>
> require(data.table);
> dt <- data.table(read.table(text="N1 N2\nA B\nC D\n", header=TRUE));
> new_col_name = "N3";
> dt[, new_col_name := NA];
>
> That creates a column literally named "new_col_name", rather than "N3" as desired.
>
> I can work around it this way:
>
> dt[, workaround := NA];
> setnames(dt, "workaround", new_col_name);
>
> I have tried wrapping the new_col_name variable in all sorts of functions such as eval(), c(), list(), quote(), etc; all of these generate an error such as:
>
> Error in `[.data.table`(dt, , `:=`(quote(new_col_name), NA)) :
>   LHS of := must be a single column name when with=TRUE. When with=FALSE the LHS may be a vector of column names or positions.
>
> Surely I am overlooking something trivial; please advise.
>
> Thanks
> George
> http://stackoverflow.com/users/1313052/gkaupas
>
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help


More information about the datatable-help mailing list