Home > Mobile >  Replacing entire characters that start or end with a specific letter or number in R
Replacing entire characters that start or end with a specific letter or number in R

Time:03-08

I am trying to replace character column values that have a value of ($100,000 - $150,000). However, there are many ranges that start with "$100,000" which I want to change to "high pay"

I was trying to use the gsub function in R but I did not know how to make it replace any value that starts with "$100,000" Keep in mind all ranges are characters.

salary salary
$100,000 - $130,000 high pay
$100,000 - $140,000 high pay
$100,000 - $150,000 high pay

I would appreciate the help.

CodePudding user response:

This should work:

salary <- c("$75,000 - $100,000", "$100,000 - $130,000", "$100,000 - $140,000", "$100,000 - $150,000")
salary[grepl("^\\$100,000", salary)] <- "high pay"
salary
# [1] "$75,000 - $100,000" "high pay"           "high pay"           "high pay"

CodePudding user response:

Is this sufficient? It won't work for salaries at $200,000 or higher. But, for what you've asked, here's a way to do it using mutate() from the dplyr package to create a new variable in the data frame:

library(dplyr)

df <- data.frame(
  salary = c(
    "$75,000 - $100,000", 
    "$100,000 - $130,000", 
    "$100,000 - $140,000", 
    "$100,000 - $150,000")
)

df %>% 
  mutate(
    description = 
      ifelse(
        grepl("^\\$100,000", salary),
        "high pay", 
        ""
      )
  )

Output:

               salary description
1  $75,000 - $100,000            
2 $100,000 - $130,000    high pay
3 $100,000 - $140,000    high pay
4 $100,000 - $150,000    high pay
  •  Tags:  
  • r
  • Related