Reputation: 6155
Following is a data frame x:
> x <- data.frame(a = c(0.1,0.1,0.1,1,1.1,1.2,2.1,3.1,3.3,3.2,3.1,2.1,2.0,0.1,0.1,1.1,2.1,3.1,4))
The first maximum value of a is 3.3 before the values start decreasing. How can I determine this value using code without looking at the plot?
Upvotes: 1
Views: 157
Reputation: 2960
"which.max" is a little bit faster:
> system.time(
+ for ( i in 1:1000000 ) { a <- x$a[which.max(diff(x$a)<0)] }
+ )
User System verstrichen
62.42 0.01 62.65
> system.time(
+ for ( i in 1:1000000 ) { b <- x[which(diff(x$a) < 0L)[1L],] }
+ )
User System verstrichen
111.43 0.00 112.14
>
The result is the same:
> a
[1] 3.3
> b
[1] 3.3
Upvotes: 2
Reputation: 92282
With base R I would go with
x[which(diff(x$a) < 0L)[1L],]
## [1] 3.3
Upvotes: 4