[R] result numeric(0) when using variable1[which(variable2="max(variable2)"]

Berend Hasselman bhh at xs4all.nl
Tue Jan 17 15:24:41 CET 2012


On 17-01-2012, at 11:35, Nerak wrote:

> Dear all,
> I have a question about the knowing for which row I have the max value of
> one of my variables.
> I calculated the Rsquared for different columns and made a list to gather
> them. I unlisted this list to create a vector with this values. I want to
> know for which column I have the max value of Rsquared.  
> The columns were always named in the same way. They always start with
> results4$depth_ following by the number. The numbers are constructed as:
> seq(1,10,0.1). But if the R squared values are now in 1 column, I don’t know
> for which column they are calculated. So I made a new data frame with both
> columns:
> R2 <- unlist(LIST) 
> Cvalue <- c(seq(1,10,0.1)) 
> results5 <- data.frame(Cvalue,R2) 
> 
> # I know I can calculate the max value of Rsquared by this way: 
> 
> max(results5$R2) 
> 
> # now I want to know to which Cvalue this belongs. I would write it like
> this: 
> results5$Cvalue[which(results5$R2 == "max(results5$R2)")] 
> # But I always get the solution: 
> numeric(0) 

You haven't provided a reproducible example.
So I tried this

set.seed(1)
x <- round(runif(10),3)
x
which.max(x)
which(x==max(x))
x
which(x=="0.945")
which(x==max(x))
which(x=="max(x)")
x[which(x=="max(x)")]

If you run this you will see that the last line results in numeric(0).

So; why are you using quotes in the which expression? Is results5$R2 a character string?
This should work

results5$Cvalue[which(results5$R2 == max(results5$R2))]

But this is shorter

results5$Cvalue[which.max[results5$R2)]

Berend



More information about the R-help mailing list