5

I have a vector of Characters named Vector, this is the output:

[1] "140222" "140207" "0" "140214" "140228" "140322" "140307" "140419" "140517" "140719" "141018" "150117" "160115"

I want to conditionally remove the only element different to the others, in this case the 0.

I tried this approach but it seems not working:

for (i in 1:length(Vector) {
    if (nchar(Vector[i]) <=3) 
    {remove(Vector[i])}
}

The error is:

Error in remove(Vector[i]) : ... must contain names or character strings".

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
GrilloRob
  • 262
  • 1
  • 3
  • 15

2 Answers2

15

First of all, you don't need to use a loop for this. This will do what you want:

Vector <- Vector[nchar(Vector) > 3]

If you wanted to specifically remove the "0", you would do this:

Vector <- Vector[Vector != "0"]

The error is caused because you're using remove on an element inside Vector, instead of on an object. In other words, remove can remove all of Vector from memory, but not elements of it. Same is true for other objects.

MDe
  • 2,478
  • 3
  • 22
  • 27
1

If you're using R interactively (otherwise it's less recommended - see here: Why is `[` better than `subset`?), you can also write:

subset(Vector, nchar(Vector) >3)
Community
  • 1
  • 1
nassimhddd
  • 8,340
  • 1
  • 29
  • 44
  • `subset()` should not be used in a non-interactive environment. – TARehman Feb 13 '15 at 21:42
  • 2
    @TARehman; your down-vote is really not constructive. 1/ The question doesn't mention it's a non-interactive environment. 2/ I think it's helpful to show a beginner the different options the language has to offer. – nassimhddd Feb 14 '15 at 13:14
  • Good edit, and I hesitated somewhat given the age of the question, but I figured that if I stumbled across it while trying to find something, so could another user. – TARehman Feb 16 '15 at 21:37