I have created a function in an R package which takes several arguments. One of these arguments is the name of a column for an R data.table.
Let's say I wanted to create a column with all values 42
. For R data.table dt
, I would do:
dt[, column_name:=42]
For R data.frame, I would do:
df$column_name = 42
I would like the function to take as an argument something that would define column_name
. For instance, the function func
called by
func(dt, col='hey')
would pass hey
as the new name of the data.table column.
Here's a concrete example
renamer = function(colname, dt){
## do calculations on dt
dt[, colname:= 42]
}
If I call the function renamer(colname = 'foo', dt=dt)
, the resulting column name will still be colname
, not the value I passed, 'foo'.
The new column should be the string 'foo'
How could I do this? I've also tried with R data.frame, or trying something with
setnames(dt, "oldname", "newname")
EDIT: I think this question should be clarified:
Here is a data.table:
> library(data.table)
> DT = data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18)
> DT
ID a b c
1: b 1 7 13
2: b 2 8 14
3: b 3 9 15
4: a 4 10 16
5: a 5 11 17
6: c 6 12 18
I would like to create a function such that the new name of the column will be the string the user passes it.
e.g.
colnamer = function(newcolumname, datatable){
## do calculations on dt
## create a column with whatever string is passed via 'newcolumnname'
}
If the user calls colnamer('foobar', DT)
, I would like the result to be
> DT
ID a b c foobar
1: b 1 7 13 ...
2: b 2 8 14 ...
3: b 3 9 15 ...
4: a 4 10 16 ...
5: a 5 11 17 ...
6: c 6 12 18 ...
colname
inrenamer
function to change or do you want to change the contents ofcolname
? In the latter case I think this would work;dt[, get(colname) := 42]
– tstevrenamer(colname = 'foo', dt=dt)
, the new column wouldfoo
– ShanZhengYangget(colname)
isError in get(colname) : object 'foo' not found
– ShanZhengYangdt[[colname]] <- 42
? – Moody_Mudskipperdata.table
expert but I think the line inrenamer
should bedt[, (colname) := 42]
. – markus