I have a function similar to this one:
isGoodNumber <- function(X) { if (X==5) return(TRUE) else return(FALSE) } I have a vector: v<-c(1,2,3,4,5,5,5,5)
I want to obtain a new vector that contains the elements of v
where isGoodNumber(v) == TRUE
How do I do this ?
Tried v [ isGoodNumber(v) == TRUE ]
but it doesn't work :-)
Thanks !!
In this article, we are going to discuss how to filter a vector in the R programming language. Filtering a vector means getting the values from the vector by removing the others, we can also say that getting the required elements is known as filtering.
The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.
The filter() function is used to subset a data frame, retaining all rows that satisfy your conditions. To be retained, the row must produce a value of TRUE for all conditions.
There is a function named "Filter" that will do exactly what you want:
Filter( isGoodNumber, v) #[1] 5 5 5 5
There would be the option of making a function that was vectorized, either by by the use of the Vectorize
function (already illustrated) or writing it with ifelse
(also mentioned) and there would be the option of a function that was "Filter"-like
isGoodNumber3 <- function(X) { X[ ifelse(X==5, TRUE,FALSE)] } isGoodNumber3(v) #[1] 5 5 5 5
I think here is the easiest method
> v<-c(1,2,3,4,5,5,5,5) > v[v==5] [1] 5 5 5 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With