简体   繁体   中英

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.

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

如果它像您描述的那么简单:

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

use sub() . Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM