0

I would like to apply the following ggplot function to a list of dataframes, each with the exact same format. This is the format of the data:

enter image description here

All datasets have same datatypes, column names, and row & column lengths. For each list of dataframes, I want to always plot xvar as Time, and yvar as Zscore.

The function I want to use is as follows.

library(ggplot2)
library(gridExtra)

Tzero = 0 
Tminus120 = -120
TEnd = 120

testIDplot <- function(data1,
                          xvar,
                          yvar){ggplot(data = data1)+
    geom_line(aes(x={{xvar}},y={{yvar}}),colour="#fd8d3c", size=0.5) +
    geom_vline(xintercept=Tzero, colour="black", size=0.8)+
    labs(x = "Time (s)", y = "Z-Score")+
    scale_x_continuous(breaks = seq(Tminus120,TEnd,60), limits = c(Tminus120,NA))+ 
    scale_y_continuous(expand = c(0, 0), limits = c(-3, 6))}

To call this function normally, I would specify testIDplot(newdata,Time,Zscore)

However, I don't know how to specify the columns when calling through a list. I tried lapply:

listofDF <- list(newdata1,newdata2,newdata3,newdata4,newdata5)
plotlist <- lapply(listofDF,testIDplot)
plotlist[1]

But this method doesn't work because of the missing aesthetics x and y.

Does anyone have any suggestions?

1
  • 4
    Try with lapply(listofDF, \(x) testIDplot(x, Time, Zscore)) Commented Jul 24, 2023 at 16:27

2 Answers 2

2

You can pass these values in the ... space of lapply:

library(tidyverse)


dfs <- map(1:4, \(x) {
  tibble(
    a = letters,
    b = runif(26, 1, 10)
  )
})

plot_df <- function(df, xvar, yvar) {
  
  ggplot(df, aes({{xvar}}, {{yvar}})) +
    geom_col()
  
}

# Testing function call for one dataset:
plot_df(dfs[[1]], a, b)

# Pass column names after the function argument in `lapply`
# (either as positional, or preferably named arguments)
lapply(dfs, plot_df, xvar = a, yvar = b)

Anonymous functions are a super-helpful and clear way as well, as suggested by Stefan above:

lapply(dfs, \(df) plot_df(df, xvar = a, yvar = b))
Sign up to request clarification or add additional context in comments.

Comments

1

You could potentially try the following, change: aes(x={{xvar}},y={{yvar}} -> x=eval(parse(xvar)), y = eval(parse(var))

Then:

lapply(listofDF, testIDplot, xvar = "Time", y = "Score". 

see this other question

Or try this:

aes(x= .data[[x_var]], y= .data[[y_var]])

this other solution

Hope this might help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.