2011-03-18 25 views
3

我有一个简单的问题,我认为。在我的数据帧我想提出的子集,其中列Quality_score等于:完美,完美* ,完美* ,好,好 **和***好sublection数据框

这在我的解决方案现在:

>Quality_scoreComplete <- subset(completefile,Quality_score == "Perfect" | Quality_score=="Perfect***" | Quality_score=="Perfect****" | Quality_score=="Good" | Quality_score=="Good***" | Quality_score=="Good****") 

有没有办法简化这种方法?像:

methods<-c('Perfect', 'Perfect***', 'Perfect****', 'Good', 'Good***','Good***') 
Quality_scoreComplete <- subset(completefile,Quality_score==methods) 

谢谢大家,

Lisanne

回答

1

一两件事,工作原理是grepl,这个搜索字符串中的模式,并返回一个逻辑指示是否它的存在。你可以在一个字符串中使用|运营商以及以表示OR和ignore.case忽略大小写:

methods<-c('Perfect', 'Perfect*', 'Perfect*', 'Good', 'Good','Good*') 

completefile <- data.frame(Quality_score = c(methods, "bad", "terrible", "abbysmal"), foo = 1) 

subset(completefile,grepl("good|perfect",Quality_score,ignore.case=TRUE)) 
1  Perfect 1 
2  Perfect* 1 
3  Perfect* 1 
4   Good 1 
5   Good 1 
6   Good* 1 

编辑:我看到现在这种情况下,灵敏度是不是一个问题,谢谢阅读障碍!你完全可以简化再到:

subset(completefile,grepl("Good|Perfect",Quality_score)) 
+0

哦,我认为是有问题的。我在另一个程序中实现了R,但是这个程序并没有对其进行regonize |任何其他选项? – Samantha 2011-03-18 10:15:45

+0

无法识别该ID不能正确评估'grepl'调用?或者你的意思是说你不能输入那个符号? – 2011-03-18 13:44:35

2

你甚至都不需要subset,检查:?"["

Quality_scoreComplete <- completefile[completefile$Quality_score %in% methods,] 

编辑:基于@Sacha Epskamp的那种评论:==表达式给出了错误的结果,因此将其更正为%in%。谢谢!问题的

例子:

> x <- c(17, 19) 
> cars[cars$speed==x,] 
    speed dist 
29 17 32 
31 17 50 
36 19 36 
38 19 68 
> cars[cars$speed %in% x,] 
    speed dist 
29 17 32 
30 17 40 
31 17 50 
36 19 36 
37 19 46 
38 19 68 
+0

如果你用'%in%'代替'==' – 2011-03-18 08:59:44

+0

@Sacha Epskamp:对,谢谢! – daroczig 2011-03-18 09:05:34

+0

感谢Sascha!它适合我! – Samantha 2011-03-18 09:30:14