【问题标题】:R: Apply family that deletes columns as part of the functionR:应用删除列的族作为函数的一部分
【发布时间】:2016-06-01 19:50:59
【问题描述】:

我正在尝试遍历矩阵中的每一行,找到具有最小值的列和列名,然后在使用该列后删除该列,以便计算新的最小值。正确答案应该是这样的:

result
1/1   50
2/2   61
3/3   72
4/4   83

Test_Matrix <- matrix(c(50:149), ncol = 10 , byrow=FALSE)
 Names <- c(1:10)
 colnames(Test_Matrix) <- Names
 rownames(Test_Matrix) <- Names


result <- t(sapply(seq(nrow(Test_Matrix)), function(i) {
  j <- which.min(Test_Matrix[i,])
  c(paste(rownames(Test_Matrix)[i], colnames(Test_Matrix)[j], sep='/'), Test_Matrix[i,j])
  drops <- colnames(Test_Matrix)[j]
  Test_Matrix[ , !(names(Test_Matrix) %in% drops)]
}))
result

第二个问题是我想在迭代期间选择行的顺序,以便它选择转到与列名同名的下一行。例如,如果最小值的列名为 5,则将删除第 5 列,然后计算名为 5 的行的最小值。

想知道这是否可行,以及这些计算是否需要循环。

作为新的 R 用户,我感谢任何帮助。 谢谢!

【问题讨论】:

    标签: r loops sapply


    【解决方案1】:

    对于您问题的第一部分:

    Test_Matrix <- matrix(c(50:149), ncol = 10 , byrow=FALSE)
    Names <- c(1:10)
    colnames(Test_Matrix) <- Names
    rownames(Test_Matrix) <- Names
    
    result <- matrix(nrow=0, ncol=2)
    
    for (i in 1:nrow(Test_Matrix)) {
      Test_Matrix <- as.matrix(Test_Matrix) #when Test_Matrix has only 1 column R converts it into a vector
      j <- which.min(Test_Matrix[i, ])
      result <- rbind(result, c(paste(rownames(Test_Matrix)[i], 
                                      colnames(Test_Matrix)[j], sep='/'), 
                                as.numeric(Test_Matrix[i,j])))
      Test_Matrix <- Test_Matrix[, -j] #remove column j
    }
    
    result
    ##      [,1]  [,2] 
    ## [1,] "1/1" "50" 
    ## [2,] "2/2" "61" 
    ## [3,] "3/3" "72" 
    ## [4,] "4/4" "83" 
    ## [5,] "5/5" "94" 
    ## [6,] "6/6" "105"
    ## [7,] "7/7" "116"
    ## [8,] "8/8" "127"
    ## [9,] "9/9" "138"
    ##[10,] "10/" "149"
    

    编辑:对于第二部分,您可以使用以下代码,而不是 for 循环:

    i <- 1
    while(length(Test_Matrix)>0) {
      Test_Matrix <- as.matrix(Test_Matrix)
      j <- which.min(Test_Matrix[i, ])
      result <- rbind(result, c(paste(rownames(Test_Matrix)[i], 
                                      colnames(Test_Matrix)[j], sep='/'), 
                                as.numeric(Test_Matrix[i,j])))
      Test_Matrix <- Test_Matrix[, -j]
      i <- as.numeric(names(j))+1
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多