Search code examples
rdata.tablerenamecalculated-columns

Compute and rename columns at the same time in data.table


I have a data.table with a column "year" containing birth years:

library(data.table)

people <- data.table("year" = 1990:1992)

I would like to rename this column to "age" and compute the values at the same time in data.table:

setnames(people, c("year"), c("age" := 2023 - "age"))

setnames(people, c("year"), c("age" := 2023 - "year"))

Why isn't my code working?


Solution

  • About "why not working?", you should check with the usage of setnames. When you type ?setnames, you see the syntax

    setnames(x,old,new,skip_absent=FALSE)
    

    and the argument new is described as below:

    Optional. It can be a function or the new column names. If a function, it will be called with old and expected to return the new column names. The new column names must be the same length as columns provided to old argument.

    You can assign a new name, but not a named column


    To make it work, you can use the chaining expression like below

    > people[, age := 2023 - year][, year := NULL][]
       age
    1:  33
    2:  32
    3:  31