根据多个列名称替换data.table中的值 [英] Replacing values in a data.table according to multiple columns names
本文介绍了根据多个列名称替换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)][]
这篇关于根据多个列名称替换data.table中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文