问题
This is one of the things that really annoys me in R. Consider the following example:
a=data.frame(x=c(1,2),y=c(3,4))
i=which(a$x==0)
At this point, i is "integer(0)" and length(i) is 0. Now if I do:
b=a[-i,]
Because I'm deleting by an empty index, I expect b to have all the data in a. But instead b is an empty data frame. I have to do this instead:
if (length(i)>0) b=a[-i,] else b=a
The same applies to matrices too. Is there a way to delete that handles empty index correctly without the if-else on my part ?
回答1:
This will solve your example above
a <- data.frame(x=c(1,2),y=c(3,4))
b <- a[a$x != 0, ]
来源:https://stackoverflow.com/questions/28798401/in-r-why-does-deleting-rows-or-cols-by-empty-index-results-in-empty-data-or