R add columns to df1 with row counter in df2 (conditional)

I have two data frames in R, as shown below ... I need to add a new column (count_orders) in df1 that contains the number of orders in df2 (or the number of customers in df2). Please, help.

> df1
  buyer city
1     A   xx
2     B   yy
3     C   zz
> df2
  order buyer item
1     1     A    1
2     2     A    2
3     3     B    1
4     4     A    2
5     5     B    1
6     6     C    3
7     7     C    4

Expected Result:

> df1
  buyer city count_orders
1     A   xx   3
2     B   yy   2
3     C   zz   2
+4
source share
3 answers

Here's the dplyr approach:

library(dplyr)
count(df2, buyer) %>% right_join(df1, "buyer")
#Source: local data frame [3 x 3]
#
#  buyer n city
#1     A 3   xx
#2     B 2   yy
#3     C 2   zz

You can use count(df2, buyer) %>% right_join(df1)and let dplyr define a column to join on its own (the β€œbuyer” in this case).

+1
source

Here a solution is possible data.tablethat performs a binary connection between df1and df2when calculating the length when connecting usingby = .EACHI

library(data.table)  
setkey(setDT(df2), buyer)  
df2[df1, list(city, count_orders = .N), by = .EACHI]
#    buyer city count_orders
# 1:     A   xx            3
# 2:     B   yy            2
# 3:     C   zz            2

( @nicolas) ( df1 )

library(data.table)  
setkey(setDT(df1), buyer)  
df1[setDT(df2)[, .N, keyby = buyer], count_orders := i.N]
+3

You can try:

df1$count_orders<-as.vector(table(df2$buyer)[as.character(df1$buyer)])
#  buyer city count_orders
#1     A   xx            3
#2     B   yy            2
#3     C   zz            2
+2
source

All Articles