Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning row number using sapply

Tags:

r

I am trying to start moving away from loops in R, but am having trouble figuring out how to return information on the progress of the sapply function. For example, if I want to process a vector and print out what row I am processing, using a loop I write:

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

How can I do the same thing with sapply? Here is the code I have.

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)

Thanks for any information.

like image 663
user44796 Avatar asked Jul 30 '26 12:07

user44796


1 Answers

I would suggest using the pbapply package for "Adding Progress Bar to '*apply' Functions"

After installing the package, run example("pbsapply") to view the provided examples for this function.

like image 63
Peter Avatar answered Aug 02 '26 01:08

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!