In R, why does deleting rows or columns by an empty index result in empty data? Or, what's the "correct" way to remove?

This is one of the things that really annoys me about 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 the length (i) is 0. Now if I do:

b=a[-i,]

      

Since I am deleting 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 is true for matrices. Is there a way to delete that correctly handles the index without an if-else on my end?

0


source to share


1 answer


This will solve your example above



 a <- data.frame(x=c(1,2),y=c(3,4))
 b <- a[a$x != 0, ]

      

+2


source







All Articles