将数据集的行与R中的另一个数据集进行比较

时间:2017-04-08 20:59:27

标签: r dataset compare

我有1400行和25列的dataset1,以及400行和5列的dataset2。这两个数据集都有一个名为ID的列。作为一个小例子,我可以像下面这样说明:

数据集1:

 ID  a1    a2
 45   1    1/1/2015
 3    5    2/2/2016
 12   12   4/29/2016

dataset2:

  ID  c1  c2  c3     c4           c5
  12   m   n   5   1/2/2015    4/29/2016
  5    c   x   4   2/3/2015       NA
  45   g   t   47  4/23/2015   1/1/2015
  45   j   t   3   1/1/2016    1/1/2015
  61   t   y   12  7/3/2015       NA
  3    r   n   18  3/3/2015    2/2/2016

(正如您可以看到dataset2中的ID是dataset1中ID的子集)

我想要的是:对于dataset1的每一行,如果列ID中的值等于dataset2的列ID中的值,则将该行dataseset2的列a2的相应值复制到新列中数据集1如下:

import logging

from allauth.account.signals import user_logged_in
from django.dispatch import receiver

logger = logging.getLogger(__name__)


@receiver(user_logged_in)
def login_logger(request, user, **kwargs):
    logger.info("{} logged in with {}".format(user.email, request))

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

如@ 42所述,你可以使用匹配。

这是匹配的示例:

# match the ID of df1 with that of df2
# then returns the index of df2 that
# matches df1
# then subset the a2 column using the above index
# then store in a new column in df1
df1$c5 <- df2$a2[match(df1$ID, df2$ID)]

以上代码的输出如下:

> df1
  ID c1 c2 c3         c4    c5
1 12  m  n  5 01/02/2015  4/29/2016
2  5  c  x  4 01/02/2015       <NA>
3 45  g  t 47 01/02/2015 01/01/2015
4 45  j  t  3 01/02/2015 01/01/2015
5 61  t  y 12 01/02/2015       <NA>
6  3  r  n 18 01/02/2015 02/02/2016

答案 1 :(得分:0)

din的答案是完美的。另一种思考方式是合并到数据框架。

数据准备

ex_data1 <- data.frame(ID = c(12, 5, 45, 45, 61, 3),
                       c1 = c("m", "c", "g", "j", "t", "r"),
                       c2 = c("n", "x", "t", "t", "y", "n"),
                       c3 = c(5, 4, 47, 3, 12, 8), 
                       c4 = c("1/2/2015", "2/3/2015", "4/23/2015",
                              "1/1/2016", "7/3/2015", "3/3/2015"),
                       stringsAsFactors = FALSE)

ex_data2 <- data.frame(ID = c(45, 3, 12),
                       a1 = c(1, 5, 12),
                       a2 = c("1/1/2015", "2/2/2016", "4/29/2016"), stringsAsFactors = FALSE)

解决方案1:使用基础R合并数据

ex_data3 <- ex_data2[, c("ID", "a2")]
names(ex_data3) <- c("ID", "c5")

m_data <- merge(ex_data1, ex_data3, by = "ID", all = TRUE)

解决方案2:使用dplyr合并数据

library(dplyr)

m_data <- ex_data1 %>%
  left_join(ex_data2, by = "ID") %>%
  select(-a1, c5 = a2)