Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive %in% function in R?

I am sure this is a simple question that has been asked many times, but this is one of those times when I find it difficult to know which terms to search for in order to find the solution. I have a simple list of lists, such as the one below:

sets <- list(S1=NA, S2=1L, S3=2:5)

> sets
$S1
[1] NA

$S2
[1] 1

$S3
[1] 2 3 4 5

And I have a scalar variable val which can take the value of any integer in sets (but will never be NA). Suppose val <- 4 -- then, what is a quick way to return a vector of TRUE/FALSE corresponding to each list in set where TRUE means val is in that list and FALSE means it is not? In this case I would want something like

[1] FALSE FALSE  TRUE

I was hoping there would be some recursive form of %in% but I haven't had luck searching for it. Thank you!

like image 378
Jon Avatar asked Apr 27 '13 01:04

Jon


People also ask

What is recursive list in R?

Lists can be recursive, meaning that you can have lists within lists. Here's an example: > b <- list(u = 5, v = 12) > c <- list(w = 13) > a <- list(b,c) > a [[1]] [[1]]$u [1] 5 [[1]]$v [1] 12 [[2]] [[2]]$w [1] 13 > length(a) [1] 2.

What is a recursive function example?

The classic example of recursive programming involves computing factorials. The factorial of a number is computed as that number times all of the numbers below it up to and including 1. For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .

What is recursive function formula?

i.e. an=an-1+a1 This formula can also be defined as Arithmetic Sequence Recursive Formula. As you can see from the sequence itself, it is an Arithmetic sequence, which consists of the first term followed by other terms and a common difference between each term is the number you add or subtract to them.

What are the 3 parts that make a function recursive?

A recursive case has three components: divide the problem into one or more simpler or smaller parts of the problem, call the function (recursively) on each part, and. combine the solutions of the parts into a solution for the problem.


1 Answers

Like this:

sapply(sets, `%in%`, x = val)
#    S1    S2    S3 
# FALSE FALSE  TRUE

I had to look at the help page ?"%in%" to find out that the first argument to %in% is named x. And for your curiosity (not needed here), the second one is named table.

like image 129
flodel Avatar answered Oct 19 '22 11:10

flodel