Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. # Generate fake data
  2. a <- as.factor(sample(0:1, 20, replace = TRUE))
  3. b <- as.factor(sample(c("a","b","c","d","e","f"), 20, replace = TRUE))
  4. c <- as.factor(sample(0:10, 20, replace = TRUE))
  5. d <- as.factor(sample(0:12, 20, replace = TRUE))
  6. y <- rnorm(20)
  7. df <- data.frame(y,a,b,c,d)
  8.  
  9. # The factor variable names are:
  10. vars <- c("a","b","c", "d")
  11.  
  12. # Loop through all the factors
  13. for (i in 1:(length(vars) - 1)){
  14. for (j in (i+1):length(vars)){
  15.  
  16. # Generate the right-hand side of the formula using
  17. # the fact that (x+y+z)^2 expands in the lm() formula
  18. # to all main and interaction terms for all two-way
  19. # interactions: (x + y + z + x:y + x:z + z:y)
  20. rhs <- c(vars[i], vars[j]) %>%
  21. paste(., collapse = "+") %>%
  22. paste0("(", ., ")", "^2")
  23.  
  24. # Generate left-hand side
  25. lhs <- paste0("y", " ~ ")
  26.  
  27. # Generate the model formula
  28. my_mod <- paste0(lhs, rhs) %>%
  29. formula()
  30.  
  31. # Fit the model, save coefficients
  32. mod_sum <- lm(my_mod, data = df)
  33. mod_coef <- mod_sum$coefficients
  34.  
  35. # Identify interaction coefficients by the ":"
  36. # symbol and keep only the interaction terms in a df
  37. int_coefs_df <- mod_coef %>%
  38. names() %>%
  39. grep(":",.) %>%
  40. mod_coef[.] %>%
  41. data.frame(estimate = .)
  42.  
  43. print(int_coefs_df)
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement