问题
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