How to sum over diagonals of data frame

后端 未结 4 2448
温柔的废话
温柔的废话 2021-02-20 16:53

Say that I have this data frame:

     1   2   3   4      
100  8   12  5   14 
99   1   6   4   3   
98   2   5   4   11  
97   5   3   7   2   
<
4条回答
  •  爱一瞬间的悲伤
    2021-02-20 17:07

    You can use row() and col() to identify row/column relationships.

    m <- read.table(text="
        1   2   3   4      
    100  8   12  5   14 
    99   1   6   4   3   
    98   2   5   4   11  
    97   5   3   7   2")
    
    vals <- sapply(2:8,
           function(j) sum(m[row(m)+col(m)==j]))
    

    or (as suggested in comments by ?@thelatemail)

    vals <- sapply(split(as.matrix(m), row(m) + col(m)), sum)
    data.frame(group=LETTERS[seq_along(vals)],sum=vals)
    

    or (@Frank)

    data.frame(vals = tapply(as.matrix(m), 
           (LETTERS[row(m) + col(m)-1]), sum))
    

    as.matrix() is required to make split() work correctly ...

提交回复
热议问题