Home > other >  r - Create One-way ANOVAs, summary statistics and plots for multiple pairs of variables using loop
r - Create One-way ANOVAs, summary statistics and plots for multiple pairs of variables using loop

Time:10-26

I am new here and quite new to programming, so any help would be greatly appreciated.

I have a dataframe df1 which looks like this:

Picture Emotion Gender Type Trial Attr_scores Fear_scores Appr_scores Avoid_scores
1 happy male human first 11 3 21 21
2 sad male human first 12 6 22 22
3 neutral male human first 13 2 23 23
4 happy male cartoon first 14 3 24 24
5 sad male cartoon first 15 6 25 25
6 neutral male cartoon first 16 2 26 26
7 happy male animal first 17 3 27 27
8 sad male animal first 18 6 28 28
9 neutral male animal first 19 2 29 29
10 happy female human first 20 3 21 30
11 sad female human first 21 6 22 31
12 neutral female human first 22 2 23 32
13 happy female cartoon first 23 3 24 33
14 sad female cartoon first 24 6 25 34
15 neutral female cartoon first 25 2 26 35
16 happy female animal first 26 3 27 36
17 sad female animal first 27 6 28 37
18 neutral female animal first 28 2 29 38

And here is the code to generate it:

Picture <- c(1:18)
Emotion <- rep(c('happy','sad','neutral'),times=6)
Gender <- rep(c('male','female'),each=9)
Type <- rep(c('human','cartoon','animal','human','cartoon','animal'),each=3)
Trial <- rep(c('first'),times=18)
Attr_scores <- c(11:28)
Fear_scores <- rep(c(3,6,2),times=6)
Appr_scores <- rep(c(21:29),times=2)
Avoid_scores <- c(21:38)
df1<-data.frame(Picture,Emotion,Gender,Type,Trial,Attr_scores,Fear_scores,Appr_scores,Avoid_scores)

I need to take several pairs of variables (one independent variable one dependent variable, e.g. Emotion Attr_scores, Emotion Fear_scores, Gender Attr_scores, Gender Avoid_scores), and for each of them: 1) run summary statistics (compare means and SDs), 2) run one-way ANOVA, 3) create a scatter plot.

So far, I have created the code for the first pair of variables (Gender Attr_scores). Here is the code:

# Summary Statistics 
library(dplyr)
group_by(df1, Gender) %>%
  summarise(
    N = n(),
    Mean = mean(Attr_scores, na.rm = TRUE),
    Sd = sd(Attr_scores, na.rm = TRUE)
  )
# ANOVA
res.aov <- aov(Attr_scores ~ Gender, data = df1)
summary(res.aov)
#Plot
gender_attr_plot <- ggplot(df1, aes(x=Gender, y=Attr_scores))   
  geom_jitter(position=position_jitter(0.2))  
  stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1), 
               geom="pointrange", color="red")
ggsave("gender_attr_plot.png", gender_attr_plot, width = 1600, height = 900, units = "px")

I can copypaste the code for each additional pair of variables and change the variable names manually each time, but this seems like a very inefficient way of doing things. Moreover, if I need to run the same analyses for any additional pair of variables, I will have to copy the entire code again just to do that.

What I want to do instead, is create a table or nested list with pairs of variables (which can be easily updated later, if additional pairs of variables are required) and write a loop that goes through these pairs of variables and performs all 3 actions (summary statistics, ANOVA and plot) for each of them.

I think it should look something like this (this is very far from an actual working code, it's just to give a general idea):

variables <- list(
c(Gender, Attr_scores),
c(Gender, Fear_scores), 
c(Type, Appr_scores), 
c(Emotion, Avoid_scores))

for(i in variables){
  library(dplyr)
  group_by(df1, variables,'[[',1) %>%
    summarise(
      N = n(),
      Mean = mean(variables,'[[',2, na.rm = TRUE),
      Sd = sd(variables,'[[',2, na.rm = TRUE)
    )
  res.aov <- aov(variables,'[[',2 ~ variables,'[[',1, data = df1)
  summary(res.aov)
  plot <- ggplot(df1, aes(x=variables,'[[',1, y=variables,'[[',2))   
    geom_jitter(position=position_jitter(0.2)) 
    stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1),
                 geom="pointrange", color="red")
  ggsave("??????.png", plot, width = 1600, height = 900, units = "px")
}

Obviously, this is not working, and I have been searching all over the internet for a solution, but my knowledge of R is not yet sufficient to figure out how to make it work. Any help would be most appreciated!

CodePudding user response:

Here is a possible solution for your task: I modified your code a little and created one function my_function with this function you get the desired output for one pair of your data set. The result is return in a list!

library(dplyr)
library(ggplot2)


my_function <- function(df, x, y) { 
# Summary
  a <- group_by(df, {{x}}) %>% 
    summarise(
      N = n(),
      Mean = mean({{y}}, na.rm = TRUE),
      Sd = sd({{y}}, na.rm = TRUE)
    )
# ANOVA
  res.aov <- aov({{y}} ~ {{x}}, data = df)
  b <- summary(res.aov)
# Plot
c <- ggplot(df1, aes(x={{x}}, y={{y}}))   
  geom_jitter(position=position_jitter(0.2))  
  stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1), 
               geom="pointrange", color="red")
  ggsave(paste0(deparse(substitute(x)), "_",
               deparse(substitute(y)), ".png"), width = 1600, height = 900, units = "px")
  
  output<-list(a,b,c)
  return(output)
  
  }

# cases 1 - 4
my_function(df1, Gender, Attr_scores)
my_function(df1, Gender, Avoid_scores)
my_function(df1, Emotion, Attr_scores)
my_function(df1, Emotion, Fear_scores)

CodePudding user response:

this may be useful

https://r4ds.had.co.nz/iteration.html#the-map-functions https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/


variables <-
  structure(list(
    x = c("Gender", "Gender", "Type", "Emotion"),
    y = c("Attr_scores", "Fear_scores", "Appr_scores", "Avoid_scores")
  ),
  class = "data.frame",
  row.names = c(NA,-4L))

variables
#>         x            y
#> 1  Gender  Attr_scores
#> 2  Gender  Fear_scores
#> 3    Type  Appr_scores
#> 4 Emotion Avoid_scores

library(tidyverse)
# GROUP
map2(
  .x = variables$x,
  .y = variables$y,
  .f = ~ group_by(df,!!sym(.x)) %>%
    summarise(
      N = n(),
      Mean = mean(!!sym(.y), na.rm = TRUE),
      Sd = sd(!!sym(.y), na.rm = TRUE)
    )) %>% 
  set_names(nm = str_c(variables$x, variables$y, sep = "#"))
#> $`Gender#Attr_scores`
#> # A tibble: 2 x 4
#>   Gender     N  Mean    Sd
#>   <chr>  <int> <dbl> <dbl>
#> 1 female     9    24  2.74
#> 2 male       9    15  2.74
#> 
#> $`Gender#Fear_scores`
#> # A tibble: 2 x 4
#>   Gender     N  Mean    Sd
#>   <chr>  <int> <dbl> <dbl>
#> 1 female     9  3.67  1.80
#> 2 male       9  3.67  1.80
#> 
#> $`Type#Appr_scores`
#> # A tibble: 3 x 4
#>   Type        N  Mean    Sd
#>   <chr>   <int> <dbl> <dbl>
#> 1 animal      6    28 0.894
#> 2 cartoon     6    25 0.894
#> 3 human       6    22 0.894
#> 
#> $`Emotion#Avoid_scores`
#> # A tibble: 3 x 4
#>   Emotion     N  Mean    Sd
#>   <chr>   <int> <dbl> <dbl>
#> 1 happy       6  28.5  5.61
#> 2 neutral     6  30.5  5.61
#> 3 sad         6  29.5  5.61


# ANOVA
map2(
  .x = variables$x,
  .y = variables$y,
  .f = ~ aov(as.formula(str_c(.y, .x, sep = "~")), data = df)
) %>%
  set_names(nm = str_c(variables$x, variables$y, sep = "#"))
#> $`Gender#Attr_scores`
#> Call:
#>    aov(formula = as.formula(str_c(.y, .x, sep = "~")), data = df)
#> 
#> Terms:
#>                 Gender Residuals
#> Sum of Squares   364.5     120.0
#> Deg. of Freedom      1        16
#> 
#> Residual standard error: 2.738613
#> Estimated effects may be unbalanced
#> 
#> $`Gender#Fear_scores`
#> Call:
#>    aov(formula = as.formula(str_c(.y, .x, sep = "~")), data = df)
#> 
#> Terms:
#>                 Gender Residuals
#> Sum of Squares       0        52
#> Deg. of Freedom      1        16
#> 
#> Residual standard error: 1.802776
#> Estimated effects may be unbalanced
#> 
#> $`Type#Appr_scores`
#> Call:
#>    aov(formula = as.formula(str_c(.y, .x, sep = "~")), data = df)
#> 
#> Terms:
#>                 Type Residuals
#> Sum of Squares   108        12
#> Deg. of Freedom    2        15
#> 
#> Residual standard error: 0.8944272
#> Estimated effects may be unbalanced
#> 
#> $`Emotion#Avoid_scores`
#> Call:
#>    aov(formula = as.formula(str_c(.y, .x, sep = "~")), data = df)
#> 
#> Terms:
#>                 Emotion Residuals
#> Sum of Squares     12.0     472.5
#> Deg. of Freedom       2        15
#> 
#> Residual standard error: 5.612486
#> Estimated effects may be unbalanced

#PLOT

f <- function(x, y) {
  gender_attr_plot <- ggplot(df, aes(x = .data[[x]], y = .data[[y]]))  
    geom_jitter(position = position_jitter(0.2))  
    stat_summary(
      fun.data = mean_sdl,
      fun.args = list(mult = 1),
      geom = "pointrange",
      color = "red"
    )
}

all_plots <- map2(.x = variables$x, .y = variables$y, .f = f)

plotnames <- str_c(variables$x, "#", variables$y, ".png") 

walk2(
  .x = plotnames,
  .y = all_plots,
  .f = ~ ggsave(
    filename = .x,
    plot = .y,
    width = 1600,
    height = 900,
    units = "px"
  )
)

Created on 2021-10-25 by the reprex package (v2.0.1)

data

Picture <- c(1:18)
Emotion <- rep(c('happy', 'sad', 'neutral'), times = 6)
Gender <- rep(c('male', 'female'), each = 9)
Type <-
  rep(c('human', 'cartoon', 'animal', 'human', 'cartoon', 'animal'),
      each = 3)
Trial <- rep(c('first'), times = 18)
Attr_scores <- c(11:28)
Fear_scores <- rep(c(3, 6, 2), times = 6)
Appr_scores <- rep(c(21:29), times = 2)
Avoid_scores <- c(21:38)
df <-
  data.frame(
    Picture,
    Emotion,
    Gender,
    Type,
    Trial,
    Attr_scores,
    Fear_scores,
    Appr_scores,
    Avoid_scores
  )
  • Related