英文:
Subset a list of matrices by common column names
问题
我想基于共享的列名来对矩阵列表进行子集操作。我的当前代码返回一个空的 mat.list
。
mat.list <- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[col])
英文:
I want to subset a list of matrices based on common/shared column names. My current code returns an empty mat.list
.
mat.list <- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[col])
答案1
得分: 0
与数据框不同,你可以使用df['colname']
来对数据框进行子集化,在R中,当对矩阵或数组进行子集化时,需要指定要沿其进行子集化的边界。换句话说,你需要在最后的lapply
中使用x[, col]
而不是x[col]
。以下是一个演示示例:
mat1 <- matrix(1:9, 3, dimnames = list(1:3, c('A', 'B', 'C')))
mat2 <- matrix(1:9, 3, dimnames = list(1:3, c('C', 'D', 'E')))
mat.list <- list(mRNA = mat1, Methylation = mat2, Protein = mat1)
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[, col])
mat.list
#> $mRNA
#> A B C
#> 1 7 8 9
#>
#> $Methylation
#> C
#> 1 2 3
#>
#> $Protein
#> A B C
#> 1 7 8 9
<sup>创建于2023年05月25日,使用reprex v2.0.2</sup>
英文:
Unlike data frames, which you can subset with df['colname']
, when subsetting a matrix or array in R, you need to specify the margin along which you are subsetting. In other words you need to do x[, col]
instead of x[col]
in your last lapply
. Here's a reprex to demonstrate:
mat1 <- matrix(1:9, 3, dimnames = list(1:3, c('A', 'B', 'C')))
mat2 <- matrix(1:9, 3, dimnames = list(1:3, c('C', 'D', 'E')))
mat.list <- list(mRNA = mat1, Methylation = mat2, Protein = mat1)
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[, col])
mat.list
#> $mRNA
#> 1 2 3
#> 7 8 9
#>
#> $Methylation
#> 1 2 3
#> 1 2 3
#>
#> $Protein
#> 1 2 3
#> 7 8 9
<sup>Created on 2023-05-25 with reprex v2.0.2</sup>
答案2
得分: 0
mat.list <- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[ , col])
英文:
mat.list <- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col <- Reduce(intersect, lapply(mat.list, colnames))
mat.list <- lapply(mat.list, function(x) x[ , col])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论