Home > other >  Give string values in vector an auto index
Give string values in vector an auto index

Time:03-12

i have two vectors:

names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")

And i need the show to slowest person, i did it with if's and if else's, but i wonder if there is easier way to do it with like auto give "Slow" = 1 , "Average" = 2 and so on. In other words attach values to them. At the end it should be vector like

names_speeds <- c(names_of_p, speed)

And then so i can compare persons and get who is faster.

CodePudding user response:

First assign names to the vector speeds then you get a named vector. After that you can use which:

names(speeds) <- names
which(speeds=="Slow")
  John Robert 
     1      4 

CodePudding user response:

You could turn speeds into an ordered factor, which would preserve the labeling while also creating an underlying numerical representation:

names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")

speeds <- factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)

names_of_p[order(speeds)]
[1] "John"   "Robert" "James"  "Adam" 

names_of_p[as.numeric(speeds) < 3]
[1] "John"   "James"  "Robert"

It might also be a good idea to store the data in a data frame rather in separate vectors:

library(tidyverse)

df <- data.frame(
  names_of_p = names_of_p,
  speeds = factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)
)

df %>% 
  arrange(speeds)

  names_of_p speeds 
  <chr>      <ord>  
1 John       Slow   
2 Robert     Slow   
3 James      Average
4 Adam       Fast   

df %>% 
  filter(as.numeric(speeds) < 3)
    
  names_of_p speeds 
  <chr>      <ord>  
1 John       Slow   
2 James      Average
3 Robert     Slow  
  • Related