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!
one way to do for a limited, and small, number of columns