在 data.table 中同时计算和重命名列

问题描述 投票:0回答:1

我有一个 data.table,其中“年”列包含出生年份:

library(data.table)

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

我想将此列重命名为“age”,并同时在 data.table 中计算值:

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

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

为什么我的代码不起作用?

data.table rename calculated-columns
1个回答
0
投票

您可以使用如下链接表达式

> people[, age := 2023 - year][, year := NULL][]
   age
1:  33
2:  32
3:  31
© www.soinside.com 2019 - 2024. All rights reserved.