理解R语言中的矢量化代码

理解R语言中的矢量化代码,r,vectorization,apply,R,Vectorization,Apply,我正试图用R来理解这个问题的答案,我为此苦苦挣扎 可以使用此代码找到R代码的数据集 library(devtools) install_github("genomicsclass/GSE5859Subset") library(GSE5859Subset) data(GSE5859Subset) ##this loads the three tables you need 问题是 编写一个函数,该函数接受一个值为e的向量和一个编码两个组的二进制向量组,并从t-test返回p值:t.test(e

我正试图用R来理解这个问题的答案,我为此苦苦挣扎

可以使用此代码找到R代码的数据集

library(devtools)
install_github("genomicsclass/GSE5859Subset")
library(GSE5859Subset)
data(GSE5859Subset) ##this loads the three tables you need
问题是

编写一个函数,该函数接受一个值为e的向量和一个编码两个组的二进制向量组,并从t-test返回p值:t.test(e[group==1],e[group==0])$p.value


现在定义g来编码案例(1)和控件(0),就像这样的g您的问题似乎是关于理解函数
apply()

有关技术说明,请参见应用

我的快速解释是:您问题中的
apply()
代码行将以下函数应用于
genexpression

myttest(e=x, group=g)
其中,
x
是每行的占位符

为了帮助理解它,该
apply()
行的
循环版本如下:

N <- nrows(geneExpression)   #so we don't have to type this twice
pvals <- numeric(N)          #empty vector to store results

# what 'apply' does (but it does it very quickly and with less typing from us)
for(i in 1:N) {
    pvals[i] <- myttest(geneExpression[i,], group=g[i])
}

N这太棒了!谢谢不过有一个问题。是不是
group=g
不是
g[i]
?也许吧。我实际上并没有从github安装包,所以我只是猜测各种对象中的数据。
myttest(e=x, group=g)
N <- nrows(geneExpression)   #so we don't have to type this twice
pvals <- numeric(N)          #empty vector to store results

# what 'apply' does (but it does it very quickly and with less typing from us)
for(i in 1:N) {
    pvals[i] <- myttest(geneExpression[i,], group=g[i])
}