On 05-Mar-08 23:37:42, zack holden wrote:> Dear list,
> I'm trying to query a string of numbers to identify where in the string
> the numbers stop increasing (where x[i] == x[i+1]). In example 1 below,
> I've adapted code from Jim Holt to do this. However, I run into
> situations where the condition is not met, as in example 2, where the
> number string is continuous. In this case, I need to specify an
> alternative outcome, where if in the loop this condition isn't met, I
> default to the max. of the number string which.max(x).
>
> Can someone tell me how to add an additional statement to example 2,
> specifying that if in the loop, the
> condition isn't found, then to give the max of the string?
>
> Thanks in advance for any replies
>
>### Example 1 ################### start with test string
> xx <- c(3,4,5,5,6,7,8,9)
> result <- NULLx1 <- which.min(x)
> for(i in x1:(length(x)-1)){
> if((x[i] == x[i+1])) result <- c(result,x[i])
># start with min, result = where in string x[i]==x[i+1]}
>
>###Example 2 ####################################
> x <- c(3,4,5,6,7,8,9,10)
> result <- NULLx1 <- which.min(x)
> for(i in x1:(length(x)-1)){
> if((x[i] == x[i+1])) result <- c(result, x[i])
># condition not met; result = NULL}
I would rather do this in the following kind of way:
### Example 1:
xx <- c(3,4,5,5,6,7,8,9)
nn <- length(xx)
if(any(xx[1:(nn-1)]==xx[2:nn])){
min(which(xx[1:(nn-1)]==xx[2:nn]))
} else max(xx)
### Result: [1] 3
### Example 2:
x <- c(3,4,5,6,7,8,9,10)
n <- length(x)
if(any(x[1:(n-1)]==x[2:n])){
min(which(x[1:(n-1)]==x[2:n]))
} else max(x)
### Result: [1] 10
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 05-Mar-08 Time: 23:45:05
------------------------------ XFMail ------------------------------