我想用"aa"
"aaa"
和""
data = data.frame(attr = c(1:4), type1=c('aa','b'), type2=c("aaa", "aa"))
data <- apply(data,2,function(x) gsub("aa",'',x))
gsub
需要每个aa而gsub(c("aa", "aaa"),'',x)
不起作用
答案 0 :(得分:2)
data <- apply(data,2,function(x) gsub("aa|aaa","",x))
attr type1 type2
[1,] "1" "" ""
[2,] "2" "b" ""
[3,] "3" "" ""
[4,] "4" "b" ""
您也可以使用
data <- apply(data,2,function(x) gsub("a{2,3}","",x))
答案 1 :(得分:1)
library(dplyr)
data2 = data %>%
mutate(type1 = recode(type1, "aa" = "", "aaa" = ""),
type2 = recode(type2, "aa" = "", "aaa" = ""))
attr type1 type2
1 1
2 2 b
3 3
4 4 b
如果你想概括一下,请从@denis回答:
data2 = data %>%
mutate_all(function(x) gsub("aa|aaa","",x))
答案 2 :(得分:1)
您只需设置选项fixed = FALSE
并删除所有内容即可。
data <- as.data.frame(apply(data, 2, function(x) gsub("a",'', x, fixed = FALSE)))
data
# attr type1 type2
# 1 1
# 2 2 b
# 3 3
# 4 4 b
答案 3 :(得分:1)
dat[2:3] <- lapply(dat[2:3], gsub, pattern = '[a]{2,}', replacement = '')
结果:
> dat
attr type1 type2
1 1
2 2 b
3 3
4 4 b
使用的数据:
dat <- data.frame(attr = c(1:4), type1 = c('aa','b'), type2 = c("aaa", "aa"))