简体   繁体   English

(R) 将 Environment 上的对象循环到函数中并导出结果

[英](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)for 循环并将 ls() 传递给 2) 函数,但无论如何,我使用的函数 (regplot) 只能到达字符向量:数据错误 [,1] :不正确的维数

  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.您可以跳过第 2 步和第 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受此评论启发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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