根据多个列名称替换data.table中的值

问题描述:

我发布了这个问题关于替换data.frame中的数据,并尝试将tyluRp建议的解决方案用于我的数据,但随后又遇到了另一个问题。

I posted this question about replacing data in a data.frame, and tried to use the solution proposed by tyluRp to my data, but then I got another problem.

我的示例数据,

df1 <- data.frame(
    c(rep("AFG", 3), rep("AUS", 3)),
    rep(c("a", "b", "c"), 2),
    rep(0, 6), 
    rep(0, 6), 
    othr = c(10:15),
    stringsAsFactors = FALSE
)

colnames(df1) <- c("Country", "Category", "2000", "2001", "Oth")

df2 <- data.frame(
    rep("AFG", 2),
    c("a", "b"), 
    c(7, 8),
    c(1, 2),
    stringsAsFactors = FALSE)
)
colnames(df2) <- c("Country", "Category", "2000", "2001")

该解决方案提议于2000年使用,并替换 df1 中的某些值b y df2

The solution proposed works for year 2000, and certain values in df1 are replaced by df2:

library(data.table)

dt1 <- setDT(df1)
dt2 <- setDT(df2)
desirable_output <- dt1[dt2, on = c("Country", "Category"), as.character(2000) := i.2000]

但是我无法进行计算对于这两年,
是我的尝试:

But I can't manage to get the calculation for both years, my attempt:

years <- c(2000:2001)

for(i in years){
    desirable_output <- dt1[dt2, on = c("Country", "Category"), as.character(i) := paste("i.", years, sep="")]
}

如何解决这种情况?我缺少的是:=

How could I solve this situation? What I'm missing about:=?

预先感谢!

一种用于有限的少量列的方法

one way to do for a limited, and small, number of columns

    dt1[dt2, on = c("Country", "Category"), `:=` (`2000` = i.2000, `2001` = i.2001)][]