Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Filter a vector using a function

Tags:

function

r

vector

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 !!

like image 873
MadSeb Avatar asked Feb 13 '12 18:02

MadSeb


People also ask

Can you filter a vector in R?

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.

How do you subset a vector in R?

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.

What does the filter function do in R?

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.


2 Answers

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 
like image 179
IRTFM Avatar answered Sep 20 '22 13:09

IRTFM


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 
like image 45
xjzhou Avatar answered Sep 19 '22 13:09

xjzhou