Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of which

Tags:

r

Am I missing something obvious here? It appears the inverse function of which is missing from base R (googling and even a search on SO for "R inverse which" returns a myriad of unrelated links)?

Well, not that I can't write one, but just to relieve my frustration with it being missing and as an R-muscle flexing challenge: how would you go about writing one?

What we need is a function like:

invwhich<-function(indices, totlength)

that returns a logical vector of length totlength where each element in indices is TRUE and the rest is FALSE.

There's bound to be a lot of ways of accomplishing this (some of which are really low hanging fruit), so argue why your solution is 'best'. Oneliner anyone?

If it takes into account some of the other parameters of which (arr.ind??), that's obviously even better...

like image 454
Nick Sabbe Avatar asked Oct 05 '11 10:10

Nick Sabbe


People also ask

What is the inverse of 4?

Answer and Explanation: The multiplicative inverse of 4 is 1/4.

What is the inverse of 3?

The answer is of course one third, or 1/3, since: 3 * 1/3 = 1. Thus the multiplicative inverse of 3 is 1/3.

What is the inverse of 5?

Multiplicative Inverse of Natural Number For example, the multiplicative inverse of 5 is 1/5.

What is the inverse of 10?

We see that the multiplicative inverse of 10 is 1/10.


1 Answers

One-liner solution:

invwhich <- function(indices, totlength) is.element(seq_len(totlength), indices)

invwhich(c(2,5), 10)
[1] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
like image 70
Andrie Avatar answered Sep 20 '22 10:09

Andrie