r-根据另一个数据帧中的每个条件计算行数



我正在尝试用R进行一个私人项目。以下问题:

我有两个数据帧。两个帧的示例表:

帧1

Home           Away
1         Lens       Paris SG
2 Rapid Vienna         Admira
3         LASK Austria Vienna
4 Shijiazhuang     Wuhan Zall
5  Sonderjyske    Midtjylland
6    Bohemians      Waterford

Frame2

# A tibble: 6 x 9
Country League  Date       Home               Away                HG    AG Res      TG
<chr>   <chr>   <chr>      <chr>              <chr>            <dbl> <dbl> <chr> <dbl>
1 Mexico  Liga MX 10/09/2020 Santos Laguna      U.N.A.M.- Pumas      1     2 A         3
2 Mexico  Liga MX 10/09/2020 Mazatlan FC        Club Tijuana         1     0 H         1
3 Mexico  Liga MX 10/09/2020 Cruz Azul          Pachuca              1     0 H         1
4 Mexico  Liga MX 09/09/2020 Club Leon          U.A.N.L.- Tigres     1     1 D         2
5 Mexico  Liga MX 09/09/2020 Puebla             Club America         2     3 A         5
6 Mexico  Liga MX 09/09/2020 Guadalajara Chivas Queretaro            1     1 D         2

现在,我想在第一个数据帧中插入一个新列,该列排除并统计第二个数据帧的直接遭遇次数,即Home==Home Team和Away==AwayTeam。是否可以在链接到另一个数据帧数据的数据帧中插入数据?

我们可以使用data.table来连接on列,同时获得频率计数

library(data.table)
setDT(df_2)[df_1, .N, on = .(home, away), by = .EACHI]
#   home away N
#1:    a    c 2
#2:    b    a 0
#3:    c    b 1

或使用base Rtable

df_1$Count <-  with(df_2, table(factor(paste(home, away),
levels = unique(paste(df_1$home, df_1$away)))))

数据

df_2 <- structure(list(home = c("a", "a", "c", "b"), away = c("c", "c", 
"b", "c")), class = "data.frame", row.names = c(NA, -4L))
df_1 <- structure(list(home = c("a", "b", "c"), away = c("c", "a", "b"
)), class = "data.frame", row.names = c(NA, -3L))

是的,您可以计算第二个数据帧中的遭遇,然后将其与第一个数据帧连接:

df_1 <- data.frame(
home = c("a", "b", "c"),
away = c("c", "a", "b")
)
df_1
#>   home away
#> 1    a    c
#> 2    b    a
#> 3    c    b
df_2 <- data.frame(
home = c("a", "a", "c", "b"),
away = c("c", "c", "b", "c")
)
df_2
#>   home away
#> 1    a    c
#> 2    a    c
#> 3    c    b
#> 4    b    c
library(dplyr)
df_2_stats <- df_2 %>% 
group_by(home, away) %>% 
summarise(number_encounters = n())
#> `summarise()` regrouping output by 'home' (override with `.groups` argument)
df_2_stats
#> # A tibble: 3 x 3
#> # Groups:   home [3]
#>   home  away  number_encounters
#>   <chr> <chr>             <int>
#> 1 a     c                     2
#> 2 b     c                     1
#> 3 c     b                     1
df_1 <- df_1 %>% 
left_join(df_2_stats, by = c("home", "away"))
df_1
#>   home away number_encounters
#> 1    a    c                 2
#> 2    b    a                NA
#> 3    c    b                 1

由reprex包于2020-09-11创建(v0.3.0(

相关内容

  • 没有找到相关文章

最新更新