替换R中的字符或字符串

时间:2016-01-20 21:41:02

标签: r replace

给定此数据框

 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")

我正在努力取代&#34; ---&#34;在df中使用&#34;&#34;(空)和&#34; 22&#34;到&#34;是&#34;输出:

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

我非常感谢你提供任何帮助。

3 个答案:

答案 0 :(得分:4)

这是一种使用查找表的方法。

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

答案 1 :(得分:2)

如果它像你描述的那样简单:

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

答案 2 :(得分:0)

使用sub()。类似的东西:

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