Home > Back-end >  Is there any way to assign a vector to another and then sort it in R
Is there any way to assign a vector to another and then sort it in R

Time:09-29

    heights = c(154,152,165,160)
    names(heights) = c("Dan","Gan","Tan","Ban")


    n=length(heights)
    for(j in c(1:n))
    {
     for(i in c(1:(n-1)))
     {
      if(heights[i]>heights[i 1])
      {
       c=heights[I]
       heights[i]=heights[i 1]
       heights[i 1]=c
      }
     }
    }
    print(heights)

#I want to sort the vector of names according to the ascending order of heights (from shorter to higher).

CodePudding user response:

The order function provides an argsort functionality, so that

names(heights)[order(heights)]

should give you what you want

CodePudding user response:

Are you looking for sort()?

sort(heights) |>
    names()

[1] "Gan" "Dan" "Ban" "Tan"
  •  Tags:  
  • r
  • Related