我有一个数据帧
test<-data.frame(A=c("aa","be","cg","dh"),B=c("i","i","i","i"))
A B
1 aa i
2 be i
3 cg i
4 dh i
我想用yes
替换B
列中的i
,如果在B
列中找到字符串e
。
那么最后,它应该是这样的
A B
1 aa i
2 be yes
3 cg i
4 dh i
我试过了
test[(grep("e", test$A)),] <- as.data.frame(lapply(test, gsub, pattern= "i", replacement="yes", test$B))
虽然这两个部分分别工作,但组合并没有给我想要的输出
有很多方法可以做到这一点。在data.table:
中有一个很好的方法test<-data.frame(A=c("aa","be","cg","dh"),B=c("i","i","i","i"))
library(data.table)
test = as.data.table(test)
test[grepl("e",A),B := "yes"]
or:
test<-data.frame(A=c("aa","be","cg","dh"),B=c("i","i","i","i"))
library(dplyr)
test = tbl_df(test)
test %>% mutate(B = ifelse(grepl("e",A),"yes",B))
ifelse
函数在这里会派上用场:
test$B <- ifelse(grepl("e", test$A), gsub("i", "yes", test$B), test$B)
首先,确保字符串是字符串而不是因子:
test<-data.frame(A=c("aa","be","cg","dh"),B=c("i","i","i","i"),
stringsAsFactors=F)
test[grep("e", test$A),]$B =
gsub(pattern= "i", replacement="yes", test[grep("e", test$A),]$B);
最好是从data.frame
切换到data.table
,然后就是这样:
test[grepl("e", A), B := gsub("i", "yes", B)];
注意:这假设你想将B中的"i"替换为"yes", "ii"替换为"yesyes", "iai"替换为"yesayes",等等…相反,如果您只想在A有"e"时将B的值设置为"yes",则如下:
test[grepl("e", A), B := "yes"];
或者当B是"i"而A是"e"时,如果你想将B的值设置为"yes",那么:
test[B=="i" & grepl("e", A), B := "yes"];