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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With