根据2个条件合并两个表,并输出平均值作为结果列

时间:2018-06-08 08:54:52

标签: r join group-by dplyr summarize

我有以下两个表:

Table_1
    ID  Interval
    1   10
    1   11
    2   11

Table_2
   ID   Interval    Rating
    1   10          0.5
    1   10          0.3
    1   11          0.1
    2   11          0.1
    2   11          0.2

输出表应如下所示:

ID  Interval    Mean Ratings
1   10          0.4
1   11          0.1
2   11          0.15

我的目标是根据两个条件/列ID和间隔连接两个表。鉴于我对相同的ID和间隔有几个评级,我想计算评级的平均值。虽然ID是唯一的(~9500),但不同ID的间隔重复(如上表所示)。我目前的方法是使用2个参数的join函数。如何根据条件ID和间隔创建Table_1和Table_2连接的最终表,并在结果列中接收平均评级?

left_join(Table_1, Table_2, by = c("ID" = "ID", "Interval" = "Interval"))

3 个答案:

答案 0 :(得分:2)

首先,您需要汇总第二个表DT2,然后使用第一个表DT1执行正确的联接。

library(data.table)

DT1[DT2[, .(Mean_Rating = mean(Rating)), .(ID, Interval)], on = c(ID = "ID", Interval = "Interval")]

给出了

   ID Interval Mean_Rating
1:  1       10        0.40
2:  1       11        0.10
3:  2       11        0.15


示例数据:

DT1 <- structure(list(ID = c(1L, 1L, 2L), Interval = c(10L, 11L, 11L
)), .Names = c("ID", "Interval"), class = c("data.table", "data.frame"
), row.names = c(NA, -3L))

DT2 <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L), Interval = c(10L, 
10L, 11L, 11L, 11L), Rating = c(0.5, 0.3, 0.1, 0.1, 0.2)), .Names = c("ID", 
"Interval", "Rating"), class = c("data.table", "data.frame"), row.names = c(NA, 
-5L))

答案 1 :(得分:1)

您可以使用dplyr left_joingroup_by,然后summarise来实现这一目标。

library(dplyr)

table1 %>% 
  left_join(table2, by = c("ID", "Interval")) %>% 
  group_by(ID, Interval) %>% 
  summarise("Mean Ratings" = mean(Rating))

## A tibble: 3 x 3
## Groups:   ID [?]
#     ID Interval `Mean Ratings`
#  <int>    <int>          <dbl>
#1     1       10           0.4
#2     1       11           0.1
#3     2       11           0.15

数据

table1 <- read.table(header = T, text="ID  Interval
    1   10
    1   11
    2   11")

table2 <- read.table(header = T, text = "ID Interval    Rating
        1   10          0.5
        1   10          0.3
        1   11          0.1
        2   11          0.1
        2   11          0.2")

答案 2 :(得分:0)

你不需要加入。相反,绑定您的表并使用组&amp;摘自dplyr。以下内容实现了您的要求:

library(dplyr)

table_1 <- data.frame("ID"= c(1,1,2),"Interval"=c (10,11,11),"Rating"= c(NA,NA,NA))
table_2 <- data.frame("ID"= c(1,1,1,2,2),"Interval"= c(10,10,11,11,11),"Rating"= c(0.5,0.3,0.1,0.1,0.2))

df1 <- bind_rows(table_1,table_2) %>% group_by(ID,Interval) %>% summarise("Mean Ratings" = mean(Rating,na.rm = TRUE))