Conditionally delete items in a vector

I have a character vector with a name Vector, this is the output:

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

I want to conditionally remove a single element other than the rest, in this case 0.

I tried this approach, but it seems to not work:

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

Mistake:

Delete error (Vector [i]): ... must contain names or character strings. "

+4
source share
2 answers

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

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

If you want to specifically remove "0", you must do this:

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

, remove Vector, . , remove Vector , . .

+10

R ( - . : ` [`, ` subset`?),

subset(Vector, nchar(Vector) >3)
+1

Source: https://habr.com/ru/post/1525804/


All Articles