首页 > 解决方案 > r 数据集根据列表中的值改变新变量

问题描述

所以,我有一个包含大量中心列表的数据框。我想添加一个列,其中每个中心都采用固定在第二个数据框中的特定值。

第一个数据库如下所示:

Centre      Date       BL_MC        BL_MP
   <chr>  <date>        <dbl>       <dbl>
 1 0RI    2019-05-19        0           0
 2 0RI    2019-05-22        0           0
 3 0RI    2019-05-29        0           0
 4 0RI    2019-05-31        0           0
5 0RI    2019-06-03        0           0
 6 0RI    2019-06-05        0           0
 7 0RI    2019-06-06        0           0
 8 0RI    2019-06-13        0           0
 9 0RI    2019-06-14        0           0
10 0RI    2019-06-17        0           0
# ... with 563,836 more rows, and 7 more
#   variables: GP_SAV_Retail <dbl>,
#   GP_SAV_W <dbl>, GP_SAV <dbl>,
#   Total_general.x <dbl>, SAV_GP_BL <dbl>,
#   BL_MP <dbl>, QRL <dbl>

第二个 :

Centre         Park
   <chr>       <dbl>
 1 1BR           252
 2 1HM           198
 3 1JC           171
 4 1LM           245
 5 1MM           149
 6 1PR           200
 7 1SX            64
 8 1VM           123
 9 2FR           168
10 2MN            94
# ... with 1,453 more rows

我想获得的输出如下:

Centre    Date      BL_MC     BL_MP     Park 
0RI       17/12/2019  45       5         328

我试图合并两个数据框,但 R 没有分配正确的值。老实说,我不知道该怎么做,因为我在 R 中很年轻。有什么想法吗?

谢谢先进

标签: rdatabasedataframevariable-assignment

解决方案


match 函数是您正在寻找的函数(在 base R 中):

db1$park = dn2$park[match(db1$center, db2$center)]

match(db1$center, db2$center)返回可以在 db2 中找到 db1 的中心的位置(db1 和 db2 是您的两个数据库)


推荐阅读