有没有办法在R中运行apply函数时打印迭代次数

时间:2016-06-03 19:16:31

标签: r iteration apply

我在一个大数据集上运行一个apply-family函数,所以我想知道是否有办法知道到目前为止如何工作,到目前为止有多少元素被查看过,或者类似的东西?

2 个答案:

答案 0 :(得分:2)

您可以考虑创建全局计数器,并指定何时打印进度,例如,只要处理了10%的数据,就可以打印通知;

counter <- 0
data <- rnorm(100)
results <- sapply(data, function(x) { 
                  counter <<- counter + 1; 
                  if(counter %in% seq(0, length(y), 10)) 
                      print(paste(counter, "% has been processed"))})

[1] "10 % has been processed"
[1] "20 % has been processed"
[1] "30 % has been processed"
[1] "40 % has been processed"
[1] "50 % has been processed"
[1] "60 % has been processed"
[1] "70 % has been processed"
[1] "80 % has been processed"
[1] "90 % has been processed"
[1] "100 % has been processed"

答案 1 :(得分:1)

您可以将打印语句添加到您正在使用的函数中,如此

apply(mtcars,2, function(i) {print(i[1])
mean(i)})

不是很漂亮但是做你想做的事