dataframe - r add columns in df1 with count of rows in df2 (conditional) -
i have 2 data frames in r below...i need add new column(count_orders) in df1 contains count of orders in df2 (or count of buyer in df2). please help.
> df1 buyer city 1 xx 2 b yy 3 c zz > df2 order buyer item 1 1 1 2 2 2 3 3 b 1 4 4 2 5 5 b 1 6 6 c 3 7 7 c 4
expected output:
> df1 buyer city count_orders 1 xx 3 2 b yy 2 3 c zz 2
here's dplyr approach:
library(dplyr) count(df2, buyer) %>% right_join(df1, "buyer") #source: local data frame [3 x 3] # # buyer n city #1 3 xx #2 b 2 yy #3 c 2 zz
you use count(df2, buyer) %>% right_join(df1)
, let dplyr figure out column join on own ("buyer" in case).
Comments
Post a Comment