Returning line number using sapply

I'm trying to start moving away from loops in R, but I'm having a hard time figuring out how to return the progress information of the sapply function. For example, if I want to process a vector and print which line 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 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.

+3


source to share


3 answers


You can only do this with a function sprintf

:

sprintf('Processing item %s, value: %s', 1:length(vec), vec^2)

      

which gives:

 [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"

      




Another option would be to define your function differently:

func <- function(x) {
  p <- paste0("Processing item ", 1:length(x))
  y <- x^2
  cbind.data.frame(p, y)
}

      

When you use func(vec)

it returns dataframe:

                    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

      

+1


source


I would advise using the pbapply

package to "Add execution line to * * apply" Functions "



After installing the package, run example("pbsapply")

to view the provided examples for this feature.

+3


source


You can manipulate indexes and access values ​​in a function:

vec = LETTERS[1:10]
func = function(x) {
  paste("Processing item ", x, ", val:" , vec[x], sep="")
}

sapply(1:length(vec),func)

      

+2


source







All Articles