library(knitr)

Observed Data

library(tidyverse)
library(psycho)


df <- psycho::affective 
plot <- df %>% 
  ggplot(aes(x=Adjusting, y=Life_Satisfaction)) +
  geom_count() +
  geom_smooth(method="loess", color="black", fill="black", alpha=0.1) +
  theme_classic()
plot

Linear Fit

Model

fit <- lm(Life_Satisfaction ~ Adjusting, data=df)

analyze(fit) 

Visualize

data_linear <- df %>% 
  select(Adjusting) %>% 
  refdata(length.out=100) %>% 
  get_predicted(fit, .)

plot <- plot +
  geom_ribbon(data=data_linear, 
              aes(y=Life_Satisfaction_Predicted, ymin=Life_Satisfaction_CI_2.5, ymax=Life_Satisfaction_CI_97.5), 
              fill="red", 
              alpha=0.1) +
  geom_line(data=data_linear, 
            aes(y=Life_Satisfaction_Predicted), 
            color="red")
plot

Polynomial fit

fit <- lm(Life_Satisfaction ~ poly(Adjusting, 2), data=df)

analyze(fit) 

Visualize

To add the predictions of this model, we use the exact same code as for the linear model.

data_poly <- df %>% 
  select(Adjusting) %>% 
  refdata(length.out=100) %>% 
  get_predicted(fit, .)

plot <- plot +
  geom_ribbon(data=data_poly, 
              aes(y=Life_Satisfaction_Predicted, ymin=Life_Satisfaction_CI_2.5, ymax=Life_Satisfaction_CI_97.5), 
              fill="blue", 
              alpha=0.1) +
  geom_line(data=data_poly, 
            aes(y=Life_Satisfaction_Predicted), 
            color="blue")
plot

Raw and Orthogonal Polynomials: Interpretation

data <- data.frame(x=seq(from=1, to=5, length.out=100),
                   y=4 - 0.6*x + 0.1*x^2 + 0.25*rnorm(100))

ggplot(data, aes(x, y)) + geom_point() + 
       geom_smooth(method = "lm", formula = y ~ poly(x, 2))

summary(lm(y ~ poly(x, 2, raw=TRUE)))
summary(lm(y ~ poly(x, 2)))

Contribute

psycho is a young package in need of affection. Therefore, if you have any advices, opinions or such, we encourage you to either let us know by opening an issue, or by contributing to the code.

Credits

This package helped you? Don't forget to cite the various packages you used :)

You can cite psycho as follows:

Previous blogposts



neuropsychology/psycho.R documentation built on Jan. 25, 2021, 7:59 a.m.