Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self reference when indexing into a vector

Tags:

r

In R, is there a way to reference a vector from within the vector?

Say I have vectors with long names:

my.vector.with.a.long.name <- 1:10

Rather than this:

my.vector.with.a.long.name[my.vector.with.a.long.name > 5]

Something like this would be nice:

> my.vector.with.a.long.name[~ > 5]
[1]  6  7  8  9 10

Or alternatively indexing by a function would be convenient:

> my.vector.with.a.long.name[is.even]
[1]  2  4  6  8 10

Is there a package that already supports this?

like image 453
andrew Avatar asked Aug 26 '14 14:08

andrew


Video Answer


1 Answers

You can use pipes which allow self-referencing with .:

library(pipeR)
my.vector.with.a.long.name %>>% `[`(.>5)
[1]  6  7  8  9 10
my.vector.with.a.long.name %>>% `[`(.%%2==0)
[1]  2  4  6  8 10
like image 187
James Avatar answered Oct 06 '22 23:10

James