You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何将data.table与部分匹配的全0矩阵合并填充对应值

解法1:直接通过矩阵行列索引赋值

这是最简单的实现方式,一行代码即可完成赋值:

library(data.table)
# 导入你提供的原始数据
DE <- structure(list(date1 = c("2000", "2001", "2003"), country = c("DE", 
"DE", "DE"), value = c(10, 20, 30)), row.names = c(NA, -3L), class = c("data.table", 
"data.frame"))

df <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = 6:5, .Dimnames = list(
    c("2000", "2001", "2002", "2003", "2004", "2005"), c("UK", 
    "DE", "FR", "SP", "IT")))

# 核心赋值逻辑:按行名、列名匹配后替换对应位置的值
df[DE$date1, DE$country] <- DE$value

运行后打印df即可得到你需要的结果:

UK DE FR SP IT
2000  0 10  0  0  0
2001  0 20  0  0  0
2002  0  0  0  0  0
2003  0 30  0  0  0
2004  0  0  0  0  0
2005  0  0  0  0  0

解法2:data.table更新连接(适合大数据量场景)

如果你后续需要用data.table格式处理结果,可以用更新连接的方式,执行效率更高:

# 先把矩阵转为data.table,保留行名作为日期列
dt_df <- as.data.table(df, keep.rownames = "date1")
# 按日期匹配后更新DE列的数值
dt_df[DE, on = .(date1), DE := i.value]

如果需要转回矩阵格式,执行以下代码即可:

res_mat <- as.matrix(dt_df[, -"date1"])
rownames(res_mat) <- dt_df$date1

内容的提问来源于stack exchange,提问作者brokkoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:33:00