根据与其他列表匹配的列名从列表填充矩阵 [英] Fill matrix from list based on column name match from other list

查看:43
本文介绍了根据与其他列表匹配的列名从列表填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据:

num.list1 <- list(1,2,1,4,5)
num.list2 <- list(2,3)
num.list3 <- list(3,5,2)

num.data.list <- list(num.list1, num.list2, num.list3)

name.list1 <- list("A","B","C","D","E")
name.list2 <- list("B","C")
name.list3 <- list("A","C","E")

name.data.list <- list(name.list1, name.list2, name.list3)

all.names <- unique(unlist(name.data.list))

my.matrix <- matrix(data = NA, nrow = length(name.data.list), ncol =     length(all.names))

colnames(my.matrix) <- all.names

我想基于my.matrix的列名与name.data.list中的值进行匹配,以num.data.list中的值填充my.matrix.

I would like to populate my.matrix with the values from num.data.list based on matching the column names of my.matrix with the values in name.data.list.

即:

      A    B    C    D    E

1     1    2    1    4    5  

2     NA   2    3    NA   NA

3     3    NA   5   NA    2

有什么想法吗?谢谢.

推荐答案

使用矩阵子设置:

library(reshape2)

nm = melt(name.data.list)

my.matrix[matrix(c(nm$L1, match(nm$value, all.names)), ncol = 2)] = unlist(num.data.list)
#      A  B C  D  E
#[1,]  1  2 1  4  5
#[2,] NA  2 3 NA NA
#[3,]  3 NA 5 NA  2

这篇关于根据与其他列表匹配的列名从列表填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆