基于另一个矩阵对一个矩阵进行子集化 [英] Subsetting one matrix based in another matrix
本文介绍了基于另一个矩阵对一个矩阵进行子集化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据 G
字符串选择 R
以获得具有相同维度的分离输出.这是我的输入:
I would like to select the R
based on G
strings to obtain separated outputs with equal dimensions. This are my inputs:
R <- 'pr_id sample1 sample2 sample3
AX-1 100 120 130
AX-2 150 180 160
AX-3 160 120 196'
R <- read.table(text=R, header=T)
G <- 'pr_id sample1 sample2 sample3
AX-1 AB AA AA
AX-2 BB AB NA
AX-3 BB AB AA'
G <- read.table(text=G, header=T)
这是我的预期输出:
AA <- 'pr_id sample1 sample2 sample3
AX-1 NA 120 130
AX-2 NA NA NA
AX-3 NA NA 196'
AA <- read.table(text=AA, header=T)
AB <- 'pr_id sample1 sample2 sample3
AX-1 100 NA NA
AX-2 NA 180 NA
AX-3 NA 120 NA'
AB <- read.table(text=AB, header=T)
BB <- 'pr_id sample1 sample2 sample3
AX-1 NA NA NA
AX-2 150 NA NA
AX-3 160 NA NA'
BB <- read.table(text=BB, header=T)
有什么执行它的想法吗?
Some idea to perform it?
推荐答案
我们对第 2 列中的 'G' 进行子集化,转换为矩阵,并使用其中的值拆分序列,创建一个新的矩阵,其中 NA ("G1") 并使用索引替换对应于R"数据集值的值.
We subset the 'G' from the 2nd column, convert to matrix, and split the sequence with the values in that, create a new matrix with NA ("G1") and using the index, we replace the values that corresponds to the "R" dataset values.
lapply(split(seq_along(as.matrix(G[-1])),
as.matrix(G[-1])), function(x) {
G1 <- matrix(NA, ncol=ncol(G)-1, nrow=nrow(G),
dimnames=list(NULL, names(G)[-1]))
G1[x] <- as.matrix(R[-1])[x]
data.frame(pr_id=R$pr_id, G1) })
#$AA
# pr_id sample1 sample2 sample3
#1 AX-1 NA 120 130
#2 AX-2 NA NA NA
#3 AX-3 NA NA 196
#$AB
# pr_id sample1 sample2 sample3
#1 AX-1 100 NA NA
#2 AX-2 NA 180 NA
#3 AX-3 NA 120 NA
#$BB
# pr_id sample1 sample2 sample3
#1 AX-1 NA NA NA
#2 AX-2 150 NA NA
#3 AX-3 160 NA NA
这篇关于基于另一个矩阵对一个矩阵进行子集化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文