In R, when you work with vectors, people often prefer to work with the whole vector at the same time, rather than looping it (see, for example, this discussion).
In a sense, R has a built-in filter and reduces functions: a way to select a subset of a vector. They are very convenient in R, and there are several ways to do this - I will show you a couple, but you will get more if you read about R and look at the code of other people on a site like this. I would also like to consider the options ?which and ?'[' , In which there are more examples than here.
The first way is to simply choose which items you want. You can use this if you know the indices of the elements you want:
x <- letters[1:10] > x [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
If we need only the first five letters, we can write:
x[1:5] x[c(1,2,3,4,5)]
You can also choose which items you do not want to use with the minus sign, for example:
x[-(6:10)]
Another way to select elements is to use a logical vector:
x <- 1:5 selection <- c(FALSE, TRUE, FALSE, TRUE, FALSE) x[selection]
This is important because we can create such a vector by placing the vector in a comparison function:
selection <- (x > 3) > selection [1] FALSE FALSE FALSE TRUE TRUE x[selection]
Again, we can choose the opposite of the comparison we use (note that since it is logical, we use ! Not - ):
x[!(x > 3)] # select all elements less than or equal to 3
If you want to perform vector comparisons, you should consider the %in% function. For instance:
x <- letters[1:10] > x %in% c("d", "p", "e", "f", "y") [1] FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE # Select all elements of x that are also "d", "p", "e", "f", or "y" x[x %in% c("d", "p", "e", "f", "y")] # And to select everything not in that vector: x[!(x %in% c("d", "p", "e", "f", "y"))]
The above examples are just a few examples; I would definitely recommend the documentation. I know this is a long post after you have already accepted the answer, but such a thing is very important and understands that it will save you a lot of time and pain in the future if you are new to R, so I thought I would share a couple of ways to do it is with you.