我的数据集由许多我要尝试清理其域的电子邮件地址组成:
id <- c(1,2,3,4,5)
email <- c('jim@chase.com','steve@aol.com','stacy@gmail.com/','chris@yahoo.com','emilio@verizon.net/')
sample <- data.frame(id,email)
我正在尝试基于包含域的导入的.txt文件删除行;例如,domains.txt包含
chase.com verizon.net
我用...读取了.txt文件
domains <- read_file('C:\\\\me\\domains.txt')
domains <- strsplit(domains, ' ')
但是随后我对如何成功清洁这些东西一无所知。我尝试了两种解决方案,一种具有regex
代码,而另一种则没有:
sample <- sample[!(paste0('^',domains,'$') %in% sample$email)]
sample$domains <- grepl(paste0('^',domains,'$'),sample$email)
sample <- subset(sample, domains == FALSE, select = c(id,email))
第一个将我的数据转换为小记号(每当我尝试显示它时都会导致Column indexes must be at most 4 if positive, not 5, 6, 7, 8, 9, 10
错误),而第二个返回所有域的FALSE
,包括那些包含在其中的域domains
变量。
当字符串在变量的任一侧也需要阅读时,如何使用变量创建“搜索并销毁” regex
?
答案 0 :(得分:0)
我们paste
将{pat}的元素paste
分隔为|
的单个字符串,以使用{{1 }}返回逻辑索引,取反(grepl
),将TRUE更改为FALSE,反之亦然,将“样本”的行作为子集
!
sample[!grepl(paste(pat, collapse="|"), sample$email), , drop = FALSE]