Frage

The code:

a <- matrix(1:10, nrow=5)
b <- c(1, 4, 1)
a[a[, 1]%in%b, ]

The answer is:

     [, 1] [, 2]
[1, ] 1      6
[2, ] 4      9

Expected output:

     [, 1] [, 2]
[1, ] 1      6
[2, ] 4      9
[3, ] 1      6

That means that, the last 1 in vector b should get the corresponding value as well. but use %in%, it seems like that the duplicated 1 was removed, I would like to keep this value, and get 3 rows in the generated matrix.

War es hilfreich?

Lösung

The syntactic sugar (together with super-speed) for this is achieved by data.table:

library(data.table)

a = as.data.table(a)
setkey(a, V1)

a[J(b)]
#   V1 V2
#1:  1  6
#2:  4  9
#3:  1  6

If b is also a data.table, it's even nicer:

b = as.data.table(b)

a[b]
#   V1 V2
#1:  1  6
#2:  4  9
#3:  1  6

Andere Tipps

I think you are over complicating things, try: a[b, ]

EDIT: Above only works by accident, as pointed out by @eddi.

Here is another way using sapply:

t(sapply(b,function(x){
  a[a[,1]==x,]
}))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top