0

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.

user
  • 23
  • 2
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Maybe you are looking for `expand.grid`? How do you expect the result to be structured? – MrFlick Nov 29 '22 at 18:48

2 Answers2

0

Using sapply to loop over vars1 and vars2

> as.vector(sapply(seq_along(vars1), function(i){
    sapply(seq_along(vars2), function(j){
      paste0(vars1[i], "*", vars2[j])
    })
  }))
 [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" 
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

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" 
rjen
  • 1,938
  • 1
  • 7
  • 19