Subtraction based on two factors

后端 未结 1 1358
走了就别回头了
走了就别回头了 2021-01-22 07:25

My dataframe looks like so:

group <- c(\"A\", \"A\", \"A\", \"A\", \"B\", \"B\", \"B\", \"B\", \"C\", \"C\", \"C\", \"C\", \"C\", \"C\")
value <- c(3:6, 1:         


        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 07:43

    Its not clear why the sample answer in the post has two identical rows in each output group and not just one but at any rate this produces similar output to that shown:

    DF <- df[!duplicated(df[-2]), ]
    f <- function(x) setNames(
                data.frame(group = x$group[1:2], as.list(- combn(x$value, 2, diff))),
                       c("group", combn(x$type, 2, paste, collapse = "_"))
                )
    
    by(DF, DF$group, f)
    

    giving:

    DF$group: A
      group d_e
    1     A  -2
    2     A  -2
    ------------------------------------------------------------ 
    DF$group: B
      group d_e
    1     B  -2
    2     B  -2
    ------------------------------------------------------------ 
    DF$group: C
      group d_e d_f e_f
    1     C  -2  -4  -2
    2     C  -2  -4  -2
    

    REVISED minor improvements.

    0 讨论(0)
提交回复
热议问题