Reputation: 9018
I have a vector called test that contains 8 elements.
I want to return a vector called points that contains the MAX and MIN of the test vector where test cannot be zero. i.e. I do not want 0 to be the minimum or the maximum
Here is my code
test<- c(1,8,2,3,4,5,0,7)
test
points <- c((1:length(test))[ (test == min(test, na.rm = TRUE) | test == max(test, na.rm = TRUE) ) && test != 0 ])
points
Right now points returns
integer(0)
I want points to return
1 2
because 1 is the index of the minimum and 2 is the index of the maximum
Thank you!
Upvotes: 2
Views: 2655
Reputation: 7905
Use range
and match
, it's faster than a custom function:
vals = range(test[test != 0])
match(vals, test)
Upvotes: 4
Reputation: 6207
You could use the match
function after removing the zero values:
test<- c(1,8,2,3,4,5,0,7)
test2 <- test[test!=0]
match(c(min(test2 ),max(test2)),test)
Upvotes: 0
Reputation: 2269
This function might do what you want...
minmax <- function(v){
v.na <- v
v.na[v==0] <- NA
return(c( which.min(v.na), which.max(v.na) ))
}
minmax(test)
All the best
Upvotes: 2