我想根据来自另一个数据表的外部值更新数据表的某些指定列中的值。根据外部数据表更新指定列中的值
我知道如何通过变量做这个变量,但我想更有效的解决方案,我可以自动化,可能使用lapply
UPDATE:我的数据(在下面的例子中相当于mtcars
)设置有其他列我不想更新。
对于可再现例如,运行第一
# Load library
library(data.table)
# load data
data(mtcars)
# create another Data Table which we'll use as external reference
# this table shows the number of decimals of those variables we want to modify in mtcars
var <- c("mpg","disp","hp")
Decimal <- c(1,3,2)
DT <- cbind.data.frame(var, Decimal)
# convert into data.table
setDT(DT)
setDT(mtcars)
我此代码段的代码,通过柱
mtcars[, mpg := mpg/10^DT[var=="mpg", Decimal] ]
mtcars[, disp := disp/10^DT[var=="disp", Decimal] ]
mtcars[, hp := hp /10^DT[var=="hp", Decimal] ]
此代码工作正常,并让所需的结果更新列。
所需的结果
用于像这样的mtcars
第一行:
> mpg disp hp
> 1: 21.0 160 110
,现在它看起来像这样:
> mpg disp hp
> 1: 2.10 0.160 1.10
是否有使用function
一个更有效的解决方案,lapply
等?
我应该更清楚@akrun。现在它工作完美! –
@RafaelPereira感谢您的反馈。 – akrun