Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting multiple rows from a matrix depending on ID given by a vector

Suppose we have a matrix m with 3 columns and a vector id with an identification for the rows:

m <- matrix(c(1,1,2,1,2,3,2,2,2,3,3,4,6,7,7,
          2,2,2,4,4,5,8,9,9),ncol=3,byrow=T)

# m
#     [,1] [,2] [,3]
#[1,]    1    1    2
#[2,]    1    2    3
#[3,]    2    2    2
#[4,]    3    3    4
#[5,]    6    7    7
#[6,]    2    2    2
#[7,]    4    4    5
#[8,]    8    9    9

id <- c(1,2,3,4,5,1,4,5)

What is the fastest way to extract the rows from m with id?

As a result I'd like to have a vector for each unique identifier in id. Something like:

##[1] 1 1 2 2 2 2
##[2] 1 2 3
##[3] 2 2 2
##[4] 3 3 4 4 4 5
##[5] 6 7 7 8 9 9

My rather poor solution is way too slow for my purposes:

pts_list <- list()
for (i in unique(id)){
  pts_list[[i]] <- as.vector(t(m[id==i,]))
}
pts_list

Here a little script to test the speed (this is really ugly...):

pts_list <- list()
m2 <- cbind(m,m,m,m)
m3 <- rbind(m2,m2,m2,m2,m2,m2,m2,m2,m2,m2)
m4 <- rbind(m3,m3,m3,m3,m3,m3,m3,m3,m3,m3)
m5 <- rbind(m4,m4,m4,m4,m4,m4,m4,m4,m4,m4)
m6 <- rbind(m5,m5,m5,m5,m5,m5,m5,m5,m5,m5)
id6 <- rep(1:8000,10)

system.time(
  for (i in unique(id6)){
    pts_list[[i]] <- as.vector(t(m6[id6==i,]))
  }
)

#   user  system elapsed 
#  8.094   1.524   9.617

Any suggestions?

like image 231
J. Jansen Avatar asked Mar 15 '23 23:03

J. Jansen


1 Answers

If you don't care about the values order you could simply do

split(m, id)
# $`1`
# [1] 1 2 1 2 2 2
# 
# $`2`
# [1] 1 2 3
# 
# $`3`
# [1] 2 2 2
# 
# $`4`
# [1] 3 4 3 4 4 5
# 
# $`5`
# [1] 6 8 7 9 7 9

If you do care, you could combine it with lapply

lapply(split(as.data.frame(m), id), function(x) c(t(x)))
# $`1`
# [1] 1 1 2 2 2 2
# 
# $`2`
# [1] 1 2 3
# 
# $`3`
# [1] 2 2 2
# 
# $`4`
# [1] 3 3 4 4 4 5
# 
# $`5`
# [1] 6 7 7 8 9 9
like image 118
David Arenburg Avatar answered Mar 17 '23 14:03

David Arenburg