Home > Net >  Looping over variables to generate interaction variables
Looping over variables to generate interaction variables

Time:11-30

For each variable in var1, I want its interaction with each variable in var2. In Stata, I can simply use a nested foreach loop to do this but I am not able to replicate the logic in R.

Stata code:

foreach var1 in
    gdp_g gdp_g_l GPCP_g GPCP_g_l
{;
foreach var2 in
    polity2l y_0 ethfrac Oil lmtnest 
{;
quietly gen `var1'_`var2' = `var1'*`var2';
};
};

Not sure about the intuition in R.

vars1 <- list("gdp_g", "gdp_g_l", "GPCP_g", "GPCP_g_l")
vars2 <- list("polity2l", "y_0", "ethfrac", "Oil", "lmtnest")

multiplyit <- function(x){
  paste(x, collapse = "*")
}

for(i in 1:length(vars1)) {
  for(j in 1:length(var2)){
    vars1[i]*vars2[j]
  }
}

Maybe I need to use a formula to multiply each unique combination of variables.

CodePudding user response:

You can use combn from combinat package to get all unique combination of pairs, then collapse all strings separated by * using paste

> library(combinat)
> combn(c(vars1, vars2), 2, fun = paste, collapse="*")
 [1] "gdp_g*gdp_g_l"     "gdp_g*GPCP_g"      "gdp_g*GPCP_g_l"    "gdp_g*polity2l"    "gdp_g*y_0"        
 [6] "gdp_g*ethfrac"     "gdp_g*Oil"         "gdp_g*lmtnest"     "gdp_g_l*GPCP_g"    "gdp_g_l*GPCP_g_l" 
[11] "gdp_g_l*polity2l"  "gdp_g_l*y_0"       "gdp_g_l*ethfrac"   "gdp_g_l*Oil"       "gdp_g_l*lmtnest"  
[16] "GPCP_g*GPCP_g_l"   "GPCP_g*polity2l"   "GPCP_g*y_0"        "GPCP_g*ethfrac"    "GPCP_g*Oil"       
[21] "GPCP_g*lmtnest"    "GPCP_g_l*polity2l" "GPCP_g_l*y_0"      "GPCP_g_l*ethfrac"  "GPCP_g_l*Oil"     
[26] "GPCP_g_l*lmtnest"  "polity2l*y_0"      "polity2l*ethfrac"  "polity2l*Oil"      "polity2l*lmtnest" 
[31] "y_0*ethfrac"       "y_0*Oil"           "y_0*lmtnest"       "ethfrac*Oil"       "ethfrac*lmtnest"  
[36] "Oil*lmtnest"      

CodePudding user response:

You can take a tidyverse approach as follows.

library(tidyverse)

map(vars1, ~ str_c(., vars2, sep = "*")) %>% 
  unlist()

# [1] "gdp_g*polity2l"    "gdp_g*y_0"         "gdp_g*ethfrac"     "gdp_g*Oil"         "gdp_g*lmtnest"    
# [6] "gdp_g_l*polity2l"  "gdp_g_l*y_0"       "gdp_g_l*ethfrac"   "gdp_g_l*Oil"       "gdp_g_l*lmtnest"  
# [11] "GPCP_g*polity2l"   "GPCP_g*y_0"        "GPCP_g*ethfrac"    "GPCP_g*Oil"        "GPCP_g*lmtnest"   
# [16] "GPCP_g_l*polity2l" "GPCP_g_l*y_0"      "GPCP_g_l*ethfrac"  "GPCP_g_l*Oil"      "GPCP_g_l*lmtnest" 
  • Related