Home > Back-end >  (R) Loop objects on Environment into a function and export results
(R) Loop objects on Environment into a function and export results

Time:07-25

I would like to export plots from several dataframes.

I tried by using a 1)for loop and by passing ls() to a 2)function but in any case, the function I use (regplot) only reaches the character vector: Error in data[, 1] : incorrect number of dimensions

  1. Example dummy data:
cbind.data.frame(x = 0:6, y = c(1, 2, 3, 6.1, 5.9, 6, 6.1)) -> data1

cbind.data.frame(x = 0:6, y = c(2, 4, 6, 12.2, 11.8, 12, 12.2)) -> data2
  1. For loop:
require(easyreg)

for (i in base::ls()) { i |> easyreg::regplot(model = 3) }
  1. Trying using a function:
test_fun <- function(x) { x |> regplot(model=3) }

test_fun(ls())
  1. What I'd like to do:
for (i in base::ls()) {
  svglite::svglite(filename = paste0(i,".svg"))
  i |> easyreg::regplot(model = 3)
  dev.off()
}

CodePudding user response:

You can skip the steps 2. and 3.

# require(svglite)
for (i in ls(pattern = "data")) { # Assuming that all the dataframes'names contain the word "data"
  svglite::svglite(filename = paste0(i,".svg"))
  get(i) |> easyreg::regplot(model = 3)
  dev.off()
}

Inspired by this comment

  • Related