Guest User

Untitled

a guest
Mar 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. > library(dplyr)
  2. > tbl <- data.frame(
  3. + A = rnorm(10),
  4. + B = rnorm(10),
  5. + C = rnorm(10)
  6. + ) %>% mutate(
  7. + y = 2 * A + rnorm(10, .1)
  8. + )
  9. > tbl
  10. A B C y
  11. 1 -1.3430281 0.06457155 -0.31477796 -3.54276780
  12. 2 -0.8045598 0.55160502 -0.04486946 -0.17595827
  13. 3 0.6432380 -0.38036302 0.30313165 2.71317260
  14. 4 0.9282322 0.92453929 1.52828109 1.41677569
  15. 5 -0.2104841 -0.31510189 -1.32938820 -0.02714028
  16. 6 -1.8264372 0.92910256 0.16072524 -5.09970701
  17. 7 0.9568248 0.42829255 -0.28423084 1.58072449
  18. 8 -1.2061661 -1.10672961 0.69626390 -3.19605711
  19. 9 0.6173230 2.74964116 0.67350556 1.78849532
  20. 10 -1.1575590 -0.01747244 -0.10611764 -3.09733526
  21.  
  22. > tidy_tbl <- tbl %>% tidyr::gather(var, x, -y)
  23. > head(tidy_tbl)
  24. y var x
  25. 1 -3.54276780 A -1.3430281
  26. 2 -0.17595827 A -0.8045598
  27. 3 2.71317260 A 0.6432380
  28. 4 1.41677569 A 0.9282322
  29. 5 -0.02714028 A -0.2104841
  30. 6 -5.09970701 A -1.8264372
  31.  
  32. > library(broom)
  33. > fitted <- tidy_tbl %>%
  34. + group_by(var) %>%
  35. + do(model = lm(y ~ x, data = .))
  36. > fitted
  37. Source: local data frame [3 x 2]
  38. Groups: <by row>
  39.  
  40. # A tibble: 3 x 2
  41. var model
  42. * <chr> <list>
  43. 1 A <S3: lm>
  44. 2 B <S3: lm>
  45. 3 C <S3: lm>
  46.  
  47. > fitted %>% tidy(model)
  48. # A tibble: 6 x 6
  49. # Groups: var [3]
  50. var term estimate std.error statistic p.value
  51. <chr> <chr> <dbl> <dbl> <dbl> <dbl>
  52. 1 A (Intercept) 0.0744 0.305 0.244 0.814
  53. 2 A x 2.46 0.288 8.54 0.0000271
  54. 3 B (Intercept) -1.05 0.945 -1.11 0.298
  55. 4 B x 0.750 0.891 0.842 0.424
  56. 5 C (Intercept) -0.842 0.920 -0.915 0.387
  57. 6 C x 0.610 1.26 0.485 0.641
Add Comment
Please, Sign In to add comment