New matrix containing difference between row elements of original

后端 未结 3 1167
南笙
南笙 2020-12-22 09:53

I want to take an existing MxN matrix and create a new M-1xN matrix such that for each columns, the elements are the difference between adjacent row elements of the original

相关标签:
3条回答
  • 2020-12-22 10:22

    It's very simple for numerical data (not sure why you have characters):

    diff(m)
    

    With the character data, this should work:

    diff(matrix(as.numeric(m), dim(m)))
    
    0 讨论(0)
  • 2020-12-22 10:26

    In case you want to subtract the columns of a matrix (and not the rows), try:

    col.diff = t(diff(t(mat)))
    
    0 讨论(0)
  • 2020-12-22 10:38

    It's a bit strange with the character format, but here's a way:

    # Set up the data
    mymat<-matrix(c("17","16","15",
      "34","32","32",
      "53","47","48" ,
      "72","62","63",
      "90","78","79" ,
      "109","94","96"),nrow=6,byrow=TRUE)
    

    Use the apply function with an anonymous function centered around diff.

    apply(mymat, 2, function(x)as.character(diff(as.numeric(x))))
    
    #      [,1] [,2] [,3]
    # [1,] "17" "16" "17"
    # [2,] "19" "15" "16"
    # [3,] "19" "15" "15"
    # [4,] "18" "16" "16"
    # [5,] "19" "16" "17"
    

    If the data are numeric to begin with and a numeric result is desired, then the above could be simplified to

    apply(mymat, 2, diff)
    
    0 讨论(0)
提交回复
热议问题