0

i'm trying to get the interaction of 2 string variables but when i apply the ifelse() function the output of the interactions is numeric and not a string. I will explain in detail in the paragraphs below:

Original dataframe:

ex = rbind(cbind(c("Firm1","Firm2","Firm3"),c("Firm2","Firm3","Firm1")),cbind(c("Firm2","Firm3","Firm1"),c("Firm1","Firm2","Firm3"))) %>% as.data.frame()
 V1    V2
1 Firm1 Firm2
2 Firm2 Firm3
3 Firm3 Firm1
4 Firm2 Firm1
5 Firm3 Firm2
6 Firm1 Firm3

Desired Output:

     V1    V2 interaction
1 Firm1 Firm2           Firm1.Firm2
2 Firm2 Firm3           Firm2.Firm3
3 Firm3 Firm1           Firm3.Firm1
4 Firm2 Firm1           Firm1.Firm2
5 Firm3 Firm2           Firm2.Firm3
6 Firm1 Firm3           Firm3.Firm1

Actual Output:

ex$interaction = ifelse(ex$V1 > ex$V2, interaction(ex$V1,ex$V2),interaction(ex$V2,ex$V1))

     V1    V2 interaction
1 Firm1 Firm2           2
2 Firm2 Firm3           6
3 Firm3 Firm1           3
4 Firm2 Firm1           2
5 Firm3 Firm2           6
6 Firm1 Firm3           3

The thing that i need is that the interaction between 2 variables are independently of their order, for example: Firm 1, firm 2 have an interaction 'Firm1.Firm2', and Firm2, Firm1 have the same interaction 'Firm1.Firm2'. I can't use the numbers because i have another dataframe with different number of observations so the numbers that every pair have are not the same between the 2 dataframes so i need explicetly the interaction to include the Variables string values. Any help is useful, thanks!.

  • Yes, that's documented behavior of ifelse. You could use dplyr::if_else instead. – Roland Feb 19 '21 at 17:01
  • You can also use `replace` (base R), though its arguments are slightly different: `replace(interaction(ex$V2,ex$V1), ex$V1 > ex$V2, interaction(ex$V1,ex$V2))`. – r2evans Feb 19 '21 at 17:55

0 Answers0