Search code examples
rlineoperation

R row operation line i - line j


I need do to calculate the difference between consecutive lines. Is there a clever way to do it? The solution below works. Thanks

pos=data.frame(position=c(1,2,3),value=c(1.3,2.7,3.1))
     position value
  1        1   1.3
  2        2   2.7
  3        3   3.1

r=NULL; rnome=NULL 
for(i in seq(1,length(pos[,1])-1))  
    for(j in seq(i+1,length(pos[,1]))) 
        r=rbind(r,c(levels=paste0(pos$level[i],'-', pos$level[j]), dif=pos$value[j]-pos$value[i]))

> r
    levels dif  
[1,] "1-2"  "1.4"
[2,] "1-3"  "1.8"
[3,] "2-3"  "0.4"

Solution

  • The combn function can help you to generalize the code a bit. This seems a bit more elegant:

    pos <- data.frame(position=c(1,2,3),value=c(1.3,2.7,3.1))
    
    ans <- data.frame(levels = combn(pos$position, 2, FUN = paste, collapse = "-"),
                      dif = combn(pos$value, 2, FUN = diff))
    print(ans)
    #  levels dif
    #1    1-2 1.4
    #2    1-3 1.8
    #3    2-3 0.4
    
    # Get all combinations:
    comb <- expand.grid(pos$position, pos$position)
    lvls <- with(comb, paste0(Var1, "-", Var2))
    difs <- with(comb, Var1 - Var2)
    ans2 <- data.frame(levels = lvls, dif = difs)
    print(ans2)
    #  levels dif
    #1    1-1   0
    #2    2-1   1
    #3    3-1   2
    #4    1-2  -1
    #5    2-2   0
    #6    3-2   1
    #7    1-3  -2
    #8    2-3  -1
    #9    3-3   0