【问题标题】:How use (only) for-loop for this operation?如何(仅)使用 for 循环进行此操作?
【发布时间】:2016-04-18 13:58:06
【问题描述】:

我有这个矩阵:

A <- matrix(c(1,2,4,3,5,7,5,7,6,6,9,
              5.9,9,11,8,4.5,5.5,7.9,
              21,6.7,13.6,3.5,5,6,6,
              7.9,1,67,4,2), ncol=3, byrow=T)

还有这个向量:

B <- c(2 ,3, 4)

我会得到这个预期的结果:

      X1   X2   X3
 [1,]  4.0 14.0 22.9   
 [2,]  8.0 21.0 26.9
 [3,] 11.0 27.0 27.8
 [4,] 15.0 25.5 35.4
 [5,] 13.5 23.2 35.5
 [6,] 25.5 17.2 28.5
 [7,] 24.5 19.6 22.6
 [8,]  9.5 16.9   NA
 [9,] 73.0   NA   NA
[10,]   NA   NA   NA

# the operation under the eventually code is:
col 1: 
    A[1,1]+A[2,1]=1+3=4 # first result for first column. 
    A[2,1]+A[3,1]=3+5=8 # second result for first column
    . . .   
    A[9,1]+A[10,1]=6+67= 73 #last expected result for first column

col 2 : 
            A[1,2]+A[2,2]+A[3,2]=2+5+7=14 # first result for second column. 
            A[2,2]+A[3,2]+A[4,2]=5+7+9=21 # second result for second column
             . . .
            A[8,2]+A[9,2]+A[10,2]=5+7.9+4=16.9 #last expected result for second column
and so on for the third columns of matrix A accordingly to the values of vector B.

我尝试使用此代码:

res <- data.frame(matrix(ncol=ncol(A),nrow=nrow(A)))
res_tot <- data.frame(matrix(ncol=ncol(A),nrow=nrow(A)))
for (j in 1:ncol(A)){
    for(t in 1:nrow(A)){
      res <- A[t+B[j],j]
       res_tot[t,j] <- res
    }
  }

但索引不正确。现在,如果可能的话,我会只使用for 循环和使用索引(如i,j,k 等...)的代码,而不使用包中的mapply、rollSum 等功能。 是否可以?请...

【问题讨论】:

    标签: r for-loop


    【解决方案1】:

    我会运行sapplyfor 循环的组合。当然你也可以使用嵌套的sapply 函数。

    res <- NULL
    for (j in 1:3){
     tmp <-   sapply(1:nrow(A), function(i) ifelse((i+j > nrow(A), NA, sum(A[i:(i+j), j])))
     res <- cbind(res,tmp);colnames(res) <- NULL
    }
    res
          [,1] [,2] [,3]
     [1,]  4.0 14.0 22.9
     [2,]  8.0 21.0 26.9
     [3,] 11.0 27.0 27.8
     [4,] 15.0 25.5 35.4
     [5,] 13.5 23.2 35.5
     [6,] 25.5 17.2 28.5
     [7,] 24.5 19.6 22.6
     [8,]  9.5 16.9   NA
     [9,] 73.0   NA   NA
    [10,]   NA   NA   NA
    

    编辑:没有 sapply 和向量 B,定义要总结的行数:

    B <- c(2, 3, 4)
    res <- NULL
    for (j in 1:3){
      for(i in 1:nrow(A)){
      if(i == 1) tmp2 <- NULL
      tmp <-   ifelse(( i-1+B[j] >nrow(A)),NA, sum(A[i:(i-1+B[j]),j])) 
      tmp2 <- rbind(tmp2,tmp);rownames(tmp2) <- NULL
      }
      res <- cbind(res,tmp2);colnames(res) <- NULL
    }
    

    【讨论】:

    • 但是没有sapply,只能使用for循环吗?
    • 如果 B 的值是非连续的,但例如是随机的?
    • 所以例如在我的真实操作中 B 有这个值:
    • B
    • A 列中的每个和都根据 B 的值移动
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 2023-03-28
    • 2020-08-05
    • 2021-06-09
    • 1970-01-01
    • 2015-02-12
    • 2022-07-22
    • 1970-01-01
    相关资源
    最近更新 更多