r - Can I programmatically update the type of a set of columns (to factors) in data.table? -
I would like to modify a set of columns within a data, which is the factor. If I knew the names of the columns in advance, then I think it would be straightforward.
Library (DataWabel) DT1 & lt; - data.table (a = (1: 4), b = representative (c ('a', 'b')), c = rep (c (0,1)) dt1 [, class (b)] dt1 [, B: = factor (b)] dt1 [, class (b)] but I'm not, and instead there is a list of variable names
< Code> vars.factors & lt; - C ('B', 'C') I can apply factor function to them without a problem ...
lapply (vars .factors, function x) get DT1 [, class (obtained (x)]) lapli (warfactor, function (x) dt1 [, factor (x)) lapply (wars. Factors, function (x ) DT1 [, Factor But I do not know how to reassign or update the original column in the data table.
This fails. (X): in # get (x) Error: Invalid first argument
lapply (vars.factors, function (x) dt1 [, x: = factor (get (x))]) # code> It is not ...
Lapli (warfactor, function (x) dt1 [, get (x): = factor (get (x))] # in error (x) : Object 'B' was not found NB I tried the proposed answer without any luck.
Yes, it is quite straightforward: D. 1 [, (vars.factors): = lapali (SD, AEFactor), SDCL = WARS .factors] LHS (of: = in j ), we specify the names of the columns. If a column already exists, it will be updated, otherwise, a new column will be created. In RHS, we have . Loops on all the columns in the SD (which stands for D at S ), and we call it the sd Should be with the .ccols argument. Comment later on:
Note that we should wrap LHS with () for Assessment and Find the names of the columns within the vars.factors variable. The reason is that we allow syntax. DT [, call: = value] < / Pre> When specifying the column name, there is only one column to specify that for pure convenience (without quotes) a symbol is called a call And assigns it to value To separate both of these cases, we need () () is enough to wrap it so that we can actually get value within the variable.
Comments
Post a Comment