Subset a list of matrices by common column names.

huangapple go评论70阅读模式
英文:

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 &lt;- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col &lt;- Reduce(intersect, lapply(mat.list, colnames))
mat.list &lt;- 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[&#39;colname&#39;], 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 &lt;- matrix(1:9, 3, dimnames = list(1:3, c(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;)))
mat2 &lt;- matrix(1:9, 3, dimnames = list(1:3, c(&#39;C&#39;, &#39;D&#39;, &#39;E&#39;)))

mat.list &lt;- list(mRNA = mat1, Methylation = mat2, Protein = mat1)
col &lt;- Reduce(intersect, lapply(mat.list, colnames))
mat.list &lt;- lapply(mat.list, function(x) x[, col])

mat.list
#&gt; $mRNA
#&gt; 1 2 3 
#&gt; 7 8 9 
#&gt; 
#&gt; $Methylation
#&gt; 1 2 3 
#&gt; 1 2 3 
#&gt; 
#&gt; $Protein
#&gt; 1 2 3 
#&gt; 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 &lt;- list(mRNA=as.matrix(mrna.deg), Methylation=as.matrix(diff.meth), Protein=as.matrix(protein.dep))
col &lt;- Reduce(intersect, lapply(mat.list, colnames))
mat.list &lt;- lapply(mat.list, function(x) x[ , col])

huangapple
  • 本文由 发表于 2023年5月25日 22:34:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定