2013-05-02 60 views
2

這裏是生成列表的代碼:比較列表的相應元素中的R

x = matrix(1, 4, 4) 
    x[2,2] = 5 
    x[2:3, 1] = 3 
    x 
    #  [,1] [,2] [,3] [,4] 
    #[1,] 1 1 1 1 
    #[2,] 3 5 1 1 
    #[3,] 3 1 1 1 
    #[4,] 1 1 1 1 
    res = apply(x, 2, function(i) list(m=max(i), idx=which(i == max(i)))) 
    res 
    #[[1]] 
    #[[1]]$m 
    #[1] 3 
    # 
    #[[1]]$idx 
    #[1] 2 3 
    # 
    # 
    #[[2]] 
    #[[2]]$m 
    #[1] 5 
    # 
    #[[2]]$idx 
    #[1] 2 
    # 
    # 
    #[[3]] 
    #[[3]]$m 
    #[1] 1 
    # 
    #[[3]]$idx 
    #[1] 1 2 3 4 
    # 
    # 
    #[[4]] 
    #[[4]]$m 
    #[1] 1 
    # 
    #[[4]]$idx 
    #[1] 1 2 3 4 

現在我想比較$ M在每個子列表,獲取在矩陣中的最大值和它的索引,我可以這樣做

mvector = vector('numeric', 4) 
    for (i in 1:4) { 
    mvector[i] = res[[i]]$m 
    } 
    mvector 
    #[1] 3 5 1 1 
    max_m = max(mvector) 
    max_m 
    #[1] 5 
    max_col = which(mvector == max_m) 
    max_row = res[[max_col]]$idx 
    max_row 
    #[1] 2 
    x[max_row, max_col] 
    #[1] 5 

我想知道是否有一個更簡單的方法做到這一點?

回答

3

您是否必須構建該列表?您可以在矩陣x直接工作:

最大值(您max_m):

max(x) 
# [1] 5 

其中矩陣這個值被找到(第一隻匹配):

which.max(x) 
# [1] 5 

或其行和列索引(您的max.rowmax.col):

arrayInd(which.max(x), dim(x)) 
#  [,1] [,2] 
# [1,] 2 2 

如果有多個最大值,您可以在上述兩個語句中將which.max(x)替換爲which(x == max(x)),以獲得所有這些值。