使用 apply 函数或 for 循环多次执行脚本

Multiple execution of a script either with an apply function or with a for loop

我想 运行 this 多次编写脚本(然后再做一些其他事情)。数据位于文本文件(名为 test.txt)中,格式如下:

A   B   C   D   E
1   2   2   1   9
3   5   1   3   0
2   NA  4   13  2

并使用

导入
test <- read.table("test.txt",header=TRUE)

数据可以转换为不同的格式,并且可以在没有headers的情况下使用。

我知道我应该使用 apply 函数,并且我在 Google 上搜索了很多关于使用 apply 函数和 for 循环的信息,但我无法成功实现它们。

例如,我在 运行 执行以下代码后收到一条错误消息:

for(i in names(table)){
  message("Name of the data set:", i)
  outlierKD(table, i)}

Error in eval(expr, envir, enclos) : object 'i' not found`.

我找到了关于循环索引的讨论 ,并且还发现 exists(i) returns false 而消息正确显示。

我想执行 outlier 函数,使用 apply 函数或循环检查所有数据列中的异常值。

您可以尝试这样的操作:

source("https://datascienceplus.com/rscript/outlier.R")

A = c(1, 3, 2, 2, 3)
B = c(2, 5, 0, 1, 6)
C = c(2, 1, 4, 7, 8)
D = c(1, 3, 99, 4, 2)
E = c(9, 0, 2, 8, 4)

df = data.frame(A, B, C, D, E)

x <- 0

for (i in df) {
  x <- x + 1
  names <- names(df)
  message("Variable: ", names[x])
  outlierKD(dt = df, var = i)
}

希望对您有所帮助!

在这种情况下使用 for-loop 更容易。

test <- read.table("test.txt", header=TRUE) #copied and pasted
test

source("https://datascienceplus.com/rscript/outlier.R") #function

for(i in 1:ncol(test)) outlierKD(dt=test, i)

然后在 R 控制台(交互式)中,按 Y 键显示绘图

(我想稍微修改一下脚本,并将其存储在 .r 文件中以及将多次执行它(并执行其他操作)的脚本,如下所示:)

test <- read.table("test.txt",header=TRUE)
source("outlierKD_mod.r")
source("loopscript.r")
loopscript(test)

这没有用,我开始基于@Samuel 的代码创建一个脚本(其中没有声明函数),可以 copy-pasted 进入 R 控制台。必须在 outlierKD 脚本上修改的唯一一件事是必须替换此行:

assign(as.character(as.list(match.call())$test), test, envir = .GlobalEnv)

有了这个:

test[x]=var_name

This 命令将删除异常值检查添加到数据框中的列:

test <- subset(test, select = -c(i) )