0

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
b_yang
  • 109
  • 6
  • Maybe you should *not* do this with a for loop in the first place. What are you trying to achieve? – David Arenburg Mar 01 '15 at 20:11
  • 1
    You are asking for the empty set (and getting it). – IRTFM Mar 01 '15 at 20:37
  • BondedDust, where am I asking for the empty set ? I see it as trying to remove rows via an empty set of index values, which should return me the full set of data. – b_yang Mar 01 '15 at 22:29

1 Answers1

2

This will solve your example above

 a <- data.frame(x=c(1,2),y=c(3,4))
 b <- a[a$x != 0, ]
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
dimitris_ps
  • 5,849
  • 3
  • 29
  • 55
  • Let's say I have built a list of index values into a that satisfy some condition, and then I want to do this: 'b=a[-i,]; a=a[i,]'. It's just annoying this simple, straight-forward syntax doesn't work. – b_yang Mar 01 '15 at 22:27