[SOLVED] Give string values in vector an auto index

Issue

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.

Solution

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  

Answered By – jdobres

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.