我正试图从R中的循环中移开,但在弄清楚如何返回sapply函数的进度信息时遇到了困难。例如,如果我想处理一个向量并打印出我正在处理的行,可以使用我编写的循环:
vec = c(1:10)
out = NULL
for (i in 1:length(vec)){
print(paste("Processing item ",i,sep=""))
y = vec[i]^2
out = c(out,y)
}
我怎么才能用做同样的事呢?这是我的密码。
func = function(x) {
#print (paste("Processing item ",x,sep="")) ## This is where I want to print out the row number being processed.
x^2
}
out = sapply(vec,func)
谢谢你提供的任何信息。
发布于 2017-05-23 18:33:12
只需使用sprintf
-function就可以做到这一点:
sprintf('Processing item %s, value: %s', 1:length(vec), vec^2)
这意味着:
[1] "Processing item 1, value: 1"
[2] "Processing item 2, value: 4"
[3] "Processing item 3, value: 9"
[4] "Processing item 4, value: 16"
[5] "Processing item 5, value: 25"
[6] "Processing item 6, value: 36"
[7] "Processing item 7, value: 49"
[8] "Processing item 8, value: 64"
[9] "Processing item 9, value: 81"
[10] "Processing item 10, value: 100"
另一种选择是对函数进行稍微不同的定义:
func <- function(x) {
p <- paste0("Processing item ", 1:length(x))
y <- x^2
cbind.data.frame(p, y)
}
当您现在使用func(vec)
时,它将返回一个数据文件:
p y
1 Processing item 1 1
2 Processing item 2 4
3 Processing item 3 9
4 Processing item 4 16
5 Processing item 5 25
6 Processing item 6 36
7 Processing item 7 49
8 Processing item 8 64
9 Processing item 9 81
10 Processing item 10 100
发布于 2017-05-23 15:35:55
我建议使用pbapply
包“向‘*应用’函数添加进度条”
安装软件包后,运行example("pbsapply")
查看此函数提供的示例。
发布于 2017-05-23 15:33:41
您可以相反地处理索引并访问函数中的值:
vec = LETTERS[1:10]
func = function(x) {
paste("Processing item ", x, ", val:" , vec[x], sep="")
}
sapply(1:length(vec),func)
https://stackoverflow.com/questions/44139104
复制相似问题