简体   繁体   中英

(R) Loop objects on Environment into a function and export results

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()
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM