Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally remove elements in a vector

Tags:

r

vector

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".

like image 494
GrilloRob Avatar asked Feb 07 '14 14:02

GrilloRob


2 Answers

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.

like image 144
MDe Avatar answered Oct 03 '22 01:10

MDe


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)
like image 39
nassimhddd Avatar answered Oct 03 '22 00:10

nassimhddd