matrix(c(1,2,3,4,5),nrow=5,ncol=10,byrow=FALSE) [,1] [,2] [,3] [,4] [,5]-6ren">
gpt4 book ai didi

r - R 中向量的这种 "repeating"行为是否有名称?

转载 作者:行者123 更新时间:2023-12-04 09:19:39 25 4
gpt4 key购买 nike

我注意到很多 R 黑客都在做这样的事情:

> matrix(c(1,2,3,4,5),nrow=5,ncol=10,byrow=FALSE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 1 1 1 1 1 1
[2,] 2 2 2 2 2 2 2 2 2 2
[3,] 3 3 3 3 3 3 3 3 3 3
[4,] 4 4 4 4 4 4 4 4 4 4
[5,] 5 5 5 5 5 5 5 5 5 5

基本上,如果向量的大小(在本例中为 5)小于其放入的“容器”的大小,在本例中为矩阵(大小为 5 x 10 = 50) ,它会重复自己,直到它填满容器。我认为这绝对是 R 的精巧特性,它使许多 R 代码非常简洁。有这个名字吗?以及关于此的文档?

我从 ( http://training.bioinformatics.ucdavis.edu/docs/2012/05/DAV/lectures/gene-expression-analysis/gene-expression-analysis.pdf) 的以下代码片段中注意到了这种模式。该函数基本上采用数据矩阵并执行 quantile normalization

quan.norm<-function(x,quan=0.5){
##x: p by n data matrix, where columns are the samples.
norm<-x
p<-nrow(x)
n<-ncol(x)
x.sort<-apply(x, 2, sort) ## sort genes within a sample
x.rank<-apply(x,2,rank) ## rank genes within a sample
## find the common distribution to be matched to:
qant.sort<-matrix(apply(x.sort,1,quantile, probs=quan),
+ p,n,byrow=FALSE) #***<----- HERE ***

## match each sample to the common distribution:
for (i in 1:n){
norm[,i]<-qant.sort[x.rank[,i],i]
}
return(norm)
}

我在评论中添加了 * 以查看此模式出现的位置。我对相当复杂的算法实现的简洁性感到震惊

最佳答案

正如评论中提到的,它被称为回收规则。

来自 R 简介:

Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated.

检查此链接 R manual

关于r - R 中向量的这种 "repeating"行为是否有名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com