R: How to create a new column in a data frame with "countif" values from another data frame? -


i have 1 dataframe (df1) looks follows. indicates years when company active in specific market.

company  country  year        austria  2010        germany  2010        austria  2011 b        italy    2010 

i have second dataframe (df2) looks follows. lists investments of company in country @ given time, investment type dummy variabes.

company  country  year  jointventure  m&a  greenfield        austria  2010  1             0    0        austria  2010  0             1    0        austria  2010  1             0    0 ... 

my question follows: want add new column df1, including "countif" of each investment type indicated in df2. instance, new df1:

company  country  year  count.jointventure  count.m&a  count.greenfield        austria  2010  2                   1          0        germany  2010  ...........        austria  2011 b        italy    2010 

also, how able add new columns df1 transforming these counts dummy variables (1 if >0; 0 if 0)?

thanks , sorry basic question, did not find fitting solutions in existing threads.

cheers, martin

using aggregate() , ifelse() functions

# test data df <- data.frame(company = rep("a", 3),                   country = rep("austria", 3),                   year = rep(2010, 3),                   jointventure = c(1,0,1),                   mna = c(0,1,0),                   greenfield = rep(0,3)) # new df counts <- aggregate(cbind(jointventure, mna, greenfield)~country+company+year, data = df, fun = sum)  # dummy counts$dummyjointventure <- ifelse(counts$jointventure > 0, 1, 0) counts$dummymna <- ifelse(counts$mna > 0, 1, 0) counts$dummygreenfield <- ifelse(counts$greenfield > 0, 1, 0) 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -