How to know which is the largest variable of a vector in R?

Asked

Viewed 1,763 times

1

Suppose I have the following variables:

x = 2
y = 3
z = 5

And turn them into a vector:

vetor = c(x,y,z)

I thought I’d use the function max:

max(vetor)

[1] 5

But if I use the function max returns a number to me, and I would actually like to know what the variable name is between x, y and z is the largest, in which case the variable z.

How can I know which is the largest variable of a vector in R?

  • 1

    Maybe which.max. But if you want the name, then the vector has to be a vector with names, a named vector. To create the vector will be setNames(vetor, c('x','y','z')).

4 answers

4


R does not automatically name vectors, ideally you turn it into a data frame of a line.

vetor <- data.frame(x,y,z)

Then you can make use which.max, that returns the position/variable with the highest value or call this position to have the variable and value.

which.max(vetor)
vetor[which.max(vetor)]
  • Thanks for the answer I’ll test.

2

First the vector must have names, only then can they be extracted.
You can do it like this:

vetor = c(x, y, z)

vetor <- setNames(vetor, c('x', 'y', 'z'))

vetor
#x y z 
#2 3 5 

The names are on the top line of this exit.
Another way will be:

names(vetor) <- c('x', 'y', 'z')

And then to get the name of the element corresponding to the maximum, use which.max.

names(vetor)[which.max(vetor)]
  • Thank you for the answer I will test.

1

You can solve the problem with the function sort:

sort(colnames(vetor), decreasing = TRUE)[1]
[1] "z"

Remembering that values must be named.

  • thank you for the answer I will test.

1

If you already have the vector built (like the vetor), and have only the need to find the highest value scalar, I suggest using the for with ifelse to transform its numerical vector (vetor) in a vector with names (ww) for further procedure with which.max.

ww <- NULL

for (i in 1:length(vetor)) {
  w <- vetor[i]
  ww[i] <- ifelse(w == x, "x", 
              ifelse(w == y, "y",
                     ifelse(w == z, "z", "erro")))
  rm(w)  
}

c(ww)[which.max(vetor)]
> c(ww)[which.max(vetor)]
[1] "z"
  • Thanks for the answer, I’ll test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.