Like this?
library(tidyverse)
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
df3 <- dplyr::left_join(df1, df2, by = "Group")
df3
## A tibble: 9 x 2
# Group n
# <dbl> <dbl>
#1 1 3
#2 1 3
#3 1 3
#4 2 3
#5 2 3
#6 2 3
#7 3 4
#8 3 4
#9 3 4
Edit
If the dataframes you want to merge are very large, the data.table package can offer a significant speedup, e.g.
#install.packages("microbenchmark")
library(microbenchmark)
#install.packages("data.table")
library(data.table)
dplyr_func <- function(){
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
left_join(df1, df2, by = "Group")
}
dt_func <- function(){
df1 <- tribble(~"Group", ~"n",
1, 3,
2, 3,
3, 4)
df2 <- tribble(~"Group",
1,
1,
1,
2,
2,
2,
3,
3,
3)
df1 <- setDT(df1)
df2 <- setDT(df2)
df3 <- df1[df2, on='Group']
}
microbenchmark(dplyr_func(), dt_func())
#Unit: milliseconds
# expr min lq mean median uq max neval
# dplyr_func() 2.860449 3.005662 3.550877 3.183445 3.444416 16.001694 100
# dt_func() 1.479301 1.570013 1.808001 1.698145 1.807476 6.958431 100