sleepyjoe
sleepyjoe

Reputation: 307

Replace a character or string in R

Given this data frame

 a           b
1 --- rs149201999
2 22  rs146752890
3 --- rs139377059
4 --- rs188945759
5 22  rs6518357
6 --- rs62224609

df <- read.table(header = TRUE, stringsAsFactors = FALSE,
text = "a           b
1 --- rs149201999
2 22  rs146752890
3 --- rs139377059
4 --- rs188945759
5 22  rs6518357
6 --- rs62224609")

I am trying to replace "---" in df with ""(empty) and "22" to "yes" with an output:

    a           b
1      rs149201999
2 yes  rs146752890
3      rs139377059
4      rs188945759
5 yes  rs6518357
6      rs62224609

I'd really appreciate any help on this.

Upvotes: 1

Views: 96

Answers (3)

Jota
Jota

Reputation: 17611

Here is an approach using a lookup table.

vec <- c(`---` = "", `22` = "yes")
df$a <- vec[df$a]
#    a           b
#1     rs149201999
#2 yes rs146752890
#3     rs139377059
#4     rs188945759
#5 yes   rs6518357
#6      rs62224609

Upvotes: 4

Tyler Rinker
Tyler Rinker

Reputation: 109844

If it's as simple as you describe:

df$a <- ifelse(grepl("---", df$a), "", "yes")

Upvotes: 2

Ott Toomet
Ott Toomet

Reputation: 1956

use sub(). Something like:

df$a <- sub("---", "", df$a)

Upvotes: 0

Related Questions