Multiply a data frame row-by-row

后端 未结 4 1378
花落未央
花落未央 2021-01-21 05:25

Input file:

df1 <- data.frame(row.names=c(\"w\",\"x\",\"y\",\"z\"), 
                  A=c(0,0,0,0),
                  B=c(0,1,0,0), 
                  C=c(1,         


        
4条回答
  •  我在风中等你
    2021-01-21 06:18

    dat <- read.table(textConnection("  A B C D
    + w 0 0 1 1
    + x 0 1 0 1
    + y 0 0 1 1
    + z 0 0 0 1
    + "), header=TRUE)
    > combos <- combn(rn,2)
    > combos
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,] "w"  "w"  "w"  "x"  "x"  "y" 
    [2,] "x"  "y"  "z"  "y"  "z"  "z" 
    
    apply(combos,2, function(x) c(x[1], x[2], unlist(dat[x[1],]*dat[x[2],])))
      [,1] [,2] [,3] [,4] [,5] [,6]
      "w"  "w"  "w"  "x"  "x"  "y" 
      "x"  "y"  "z"  "y"  "z"  "z" 
    A "0"  "0"  "0"  "0"  "0"  "0" 
    B "0"  "0"  "0"  "0"  "0"  "0" 
    C "0"  "1"  "0"  "0"  "0"  "0" 
    D "1"  "1"  "1"  "1"  "1"  "1" 
    

    So the final solution:

    t( apply(combos,2, function(x) c(x[1], x[2], unlist(dat[x[1],]*dat[x[2],]))) )
    

    If you convert the combos to a dataframe you would also be able to cbindmatrix as type "numeric":

     cbind( as.data.frame(t(combos)), 
            t( apply(combos,2, function(x)  
                        unlist(dat[x[1],]*dat[x[2],]))) )
    
      V1 V2 A B C D
    1  w  x 0 0 0 1
    2  w  y 0 0 1 1
    3  w  z 0 0 0 1
    4  x  y 0 0 0 1
    5  x  z 0 0 0 1
    6  y  z 0 0 0 1
    

提交回复
热议问题