开发者

How to transform a matrix with 2 columns into a multimap like structure?

开发者 https://www.devze.com 2022-12-24 00:58 出处:网络
I am wondering if there is a way to transform a matrix of 2 columns into a multimap or list of list. The first column of the matrix is an id (with possibly duplicated entries) and the 2nd column is s

I am wondering if there is a way to transform a matrix of 2 columns into a multimap or list of list.

The first column of the matrix is an id (with possibly duplicated entries) and the 2nd column is some value.

For example, if I have to following matrix

m <- matrix(c(1,2,1,3,2,4), c(3,2))

I would like to transform it into the following list

[[1]]开发者_JAVA技巧
3,4
[[2]]
2


With base functions, you can do something like this:

tapply(m[,2], m[,1], `[`)        # outputs an array
by(m, m[,1], function(m) m[,2])  # outputs a by object, which is a list

You could use plyr:

dlply(m, 1, function(m) m[,2])   # outputs a list
dlply(m, 1, `[`, 2)              # another way to do it...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号