使用从另一个 table 索引的值创建新列

Create new column with values indexed from another table

我有两个table:

table1:

Var1   Var2
01-01  dhold_1
01-01  dhold_2
01-01  dhold_3
02-01  dhold_1
02-01  dhold_2
03-01  dhold_3

table2:

md      dhold_1   dhold_2   dhold_3
01-01   1.01      1.05      1.04
02-01   1.03      0.09      0.99

我想在 table1 中创建一个新列,我们称之为 Var3。 新列应包含 table 2 中的相应值。我想您在查看最终结果时应该知道我的意思:

table1 添加新列后(目标):

Var1   Var2      Var3
01-01  dhold_1   1.01
01-01  dhold_2   1.05
01-01  dhold_3   1.04
02-01  dhold_1   1.03
02-01  dhold_2   0.09
03-01  dhold_3   0.99

我在 R 中尝试了以下操作:

table1$Var3 <- table2[match(table1$Var1,table2$md),match(table1$Var2,colnames(table2))]

上面的代码在某种程度上产生了我想要的输出,put 不仅创建了 1 个新列,而且创建了 n 个新列,每个列都包含相同的内容。鉴于我有一个更大的文件,它最终以 vector allocation error.

我花了几个小时寻找解决方案。有人有想法吗?非常感谢。

获取table2长格式然后加入。

library(dplyr)
library(tidyr)

table2 %>%
  pivot_longer(cols = -md) %>%
  right_join(table1, by = c('md' = 'Var1', 'name' = 'Var2'))

#   md    name    value
#  <chr> <chr>   <dbl>
#1 01-01 dhold_1  1.01
#2 01-01 dhold_2  1.05
#3 01-01 dhold_3  1.04
#4 02-01 dhold_1  1.03
#5 02-01 dhold_2  0.09
#6 02-01 dhold_3  0.99 

数据

我认为table1的最后一个值应该是02-01?我更正了它并在数据中使用了它。

table1 <- structure(list(Var1 = c("01-01", "01-01", "01-01", "02-01", "02-01", 
"02-01"), Var2 = c("dhold_1", "dhold_2", "dhold_3", "dhold_1", 
"dhold_2", "dhold_3")), class = "data.frame", row.names = c(NA, -6L))

table2 <- structure(list(md = c("01-01", "02-01"), dhold_1 = c(1.01, 1.03
), dhold_2 = c(1.05, 0.09), dhold_3 = c(1.04, 0.99)), 
class = "data.frame", row.names = c(NA, -2L))