R语言实例-数据过滤

1、问题

一组数据,变量有40个,就是40列。
我要做数据筛选。
1.第一列中包含语段"a11","a12","b23"。请注意是包含,实际不存在“a11”,往往是“a1120”之类的信息
2.第二列中不包含“美国”、“日本”等信息。请注意,也是不包含,而不是不等于。

请问具体的R语言语句应该怎么写?


2、解决

假设楼主的数据为一数据框,名字为“testdat”,第一列名"a",第二列名"b",则过滤语句为:

result<-subset(testdat,grepl("a11|a12|b23",testdat$a) & !grepl("美国|日本",testdat$b))


3、注意

grep()函数返回的是匹配元素的索引,grepl()返回的是匹配或不匹配的逻辑值:

grep(value = FALSE) returns a vector of the indices of the elements of x that yielded a match (or not, for invert = TRUE. This will be an integer vector unless the input is a long vector

grepl returns a logical vector (match or not for each element of x).


posted @ 2015-11-04 13:38  hongweigg  阅读(40)  评论(0)    收藏  举报