Home > Software design >  Using R, how do I replace whole cells if they contain a special character?
Using R, how do I replace whole cells if they contain a special character?

Time:10-26

I have a data frame as follows:

df <- data.frame(name=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), score=c('<2', '4', '5', '>7', '<3', '8', '>4', '4'))

I want to replace cells containing special characters with specific text, i.e. to change any cells containing "<" to "Low", and any containing ">" to "High".

The desired output is as follows:

df2 <- data.frame(name=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), score=c('Low', '4', '5', 'High', 'Low', '8', 'High', '4'))

Attempts using gsub and str_replace_all haven't worked for me so far.

CodePudding user response:

Try the following, which finds the rows with a < or > symbol using grep, then replaces the value in the score column with the relevant "high" or "low"

df[grep("<", df$score), "score"] <- "low"
df[grep(">", df$score), "score"] <- "high"

Output:

#   name score
# 1    A   low
# 2    B     4
# 3    C     5
# 4    D  high
# 5    E   low
# 6    F     8
# 7    G  high
# 8    H     4
  •  Tags:  
  • r
  • Related