gpt4 book ai didi

r - 将 data.table/data.frame 与部分匹配的矩阵匹配

转载 作者:行者123 更新时间:2023-12-04 12:31:17 24 4
gpt4 key购买 nike

我正在尝试合并以下 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"))

date1 country value
1: 2000 DE 10
2: 2001 DE 20
3: 2003 DE 30

我想将它与一个带 0 的矩阵合并:

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

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

这样所需的输出如下:

     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

最佳答案

我们可以使用行/列索引将“value”列从“DE”分配给“df”

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

关于r - 将 data.table/data.frame 与部分匹配的矩阵匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68884713/

24 4 0