Reputation: 299
i am trying my hand at a private project with R. Following problem:
I have two data frames. Exemplary the tables of the two frames:
Frame1
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
now I want to insert a new column in the first data frame which excludes and counts the number of direct encounters from the second data frame, i.e. Home == Home Team and Away == AwayTeam. Is it possible to insert data in a dataframe that is linked to data from another dataframe?
Upvotes: 2
Views: 534
Reputation: 886938
We can use data.table
to do a join on
the columns while getting the frequency count
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
Or using base R
with table
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))
Upvotes: 2
Reputation: 10365
Yes, you can calculate the encounters in the second data.frame and then join this with the first data.frame:
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
Created on 2020-09-11 by the reprex package (v0.3.0)
Upvotes: 0