Replacing values in a data.table according to mult

2019-08-17 04:33发布

This question already has an answer here:

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.

My example data,

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")

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:=?

Thanks in advance!

标签: r data.table
1条回答
【Aperson】
2楼-- · 2019-08-17 05:15

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

    dt1[dt2, on = c("Country", "Category"), `:=` (`2000` = i.2000, `2001` = i.2001)][]
查看更多
登录 后发表回答