Alternative to which() when no match is found in R

微笑、不失礼 提交于 2019-12-12 01:28:42

问题


The which command removes all rows of data if no element was TRUE. Demonstrating with the iris dataset, let's try to remove rows for a non-existing species.

dim(iris[-which(iris$Species=="nonsense"),])
# [1] 0 5

All rows are deleted, but using the condition directly returns the expected result.

dim(iris[iris$Species!="nonsense",])
# [1] 150   5

This issue was addressed here, and the accepted answer suggested the != solution above. However, I need to store the condition result in a variable.

x <- which(iris$Species=="nonsense")

Should I instead use a logical variable to prevent problems with which?

x <- iris$Species=="nonsense"

What is the best and safest practice?

来源:https://stackoverflow.com/questions/37814729/alternative-to-which-when-no-match-is-found-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!