[R] How to quickly find the position of the first non-zero element of a vector
Bryan Keller
bskeller at wisc.edu
Wed Sep 16 01:51:19 CEST 2009
Anyone familiar with a quicker method to find the position of the first non-zero element of a vector?
#The first way:
print(min(which(vector != 0)))
#The second way:
for(i in 1:length(vector)) {
if (vector[i] != 0) {
print(i)
break
}
}
The first way seems to be faster for larger vectors (or when the first non-zero is deeper in)...
vlarge <- c(numeric(20),1:20)
#Method 1:
system.time(
for (i in 1:30000) {
min(which(vlarge != 0))})
# user system elapsed
# 0.49 0.00 0.48
#Method 2:
system.time(
for (i in 1:30000) {
for (i in 1:40) {
if (vlarge[i] != 0) {
break
}
}})
# user system elapsed
# 0.99 0.02 0.99
--------------------------------------------------
The second way seems to be faster for smaller vectors (or when the first non-zero is closer to the front)...
vsmall <- c(numeric(5),1:5)
#Method 1:
system.time(
for (i in 1:30000) {
min(which(vsmall != 0))})
# user system elapsed
# 0.41 0.00 0.42
#Method 2:
system.time(
for (i in 1:30000) {
for (i in 1:10) {
if (vsmall[i] != 0) {
break
}
}})
# user system elapsed
# 0.31 0.02 0.31
Or, might the fastest way be to choose between the two methods on-the-fly based on length of the vector, etc.?
Bryan
-------------
Bryan Keller, Doctoral Student/Project Assistant
Educational Psychology - Quantitative Methods
The University of Wisconsin - Madison
More information about the R-help
mailing list