3

I have a simple questioon I think. In my dataframe I would like to make subset where column Quality_score is equal to: Perfect, Perfect*, Perfect*, Good, Good** and Good***

This in my solution by now:

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

Is there a way to simplify this method? Like:

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

Thank you all,

Lisanne

4

2 回答 2

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
于 2011-03-18T08:58:15.573 回答
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))
于 2011-03-18T08:57:22.617 回答