Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何按3'进行索引;s在for循环R中_R_For Loop_Indexing - Fatal编程技术网

如何按3'进行索引;s在for循环R中

如何按3'进行索引;s在for循环R中,r,for-loop,indexing,R,For Loop,Indexing,我有一个39列宽的矩阵,我想得到前三列的行平均值,然后是下三列。所以在完成所有工作后,我总共有13列。三元组是我想要使用的索引,但它只是从1:39生成一个向量 Triple <- c(1:3, 4:6, 7:9, 10:12, 13:15, 16:18, 19:21, 22:24, 25:27, 28:30, 31:33, 34:36, 37:39) AveFPKM <- matrix(nrow=54175, ncol=13) for (i in 1:39){ Ave &l

我有一个39列宽的矩阵,我想得到前三列的行平均值,然后是下三列。所以在完成所有工作后,我总共有13列。三元组是我想要使用的索引,但它只是从1:39生成一个向量

Triple <- c(1:3, 4:6, 7:9, 10:12, 13:15, 16:18, 19:21, 22:24, 25:27, 28:30, 31:33, 34:36,   37:39)

AveFPKM <- matrix(nrow=54175, ncol=13)
for (i in 1:39){
  Ave <- rowMeans(AllFPKM[,i:i+2])
  AveFPKM[,i] <- Ave
  i+2
}

Triple通过指定一些维度和
应用,您可以非常轻松地获得结果。下面是一个较小的示例:

test <- matrix(1:36,ncol=12)

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]    1    4    7   10   13   16   19   22   25    28    31    34
#[2,]    2    5    8   11   14   17   20   23   26    29    32    35
#[3,]    3    6    9   12   15   18   21   24   27    30    33    36
或者通常,假设列数始终可以被组大小整除:

grp.row.mean <- function(x,grpsize) {
  apply(structure(x,dim=c(nrow(x),grpsize,ncol(x)/grpsize)),c(1,3),mean)
}
grp.row.mean(test,3)

grp.row.mean这里有一个使用
sapply
的解决方案,利用我们知道的列数正好是3的倍数:

sapply(1:13, function(x) {
  i <- (x-1)*3 + 1    # Get the actual starting index
  rowMeans(AveFPKM[,i:(i+2)])
})
sapply(1:13,函数(x){

我为什么不把矩阵改成13列,然后取平均值呢?你可以看看关于改形的一些想法非常感谢,这很有帮助。
sapply(1:13, function(x) {
  i <- (x-1)*3 + 1    # Get the actual starting index
  rowMeans(AveFPKM[,i:(i+2)])
})