Multiply a data frame row-by-row

后端 未结 4 1375
花落未央
花落未央 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:05

    If you want to multiply rows, I recommend converting to a matrix:

    > m = as.matrix(df1)
    
    > m["x", ] * m["y", ]
    A B C D 
    0 0 0 1 
    

    The specific result you want you could get with plyr,

    library(plyr)
    
    ldply(1:(nrow(m)-1), function(i)
        ldply((i+1):nrow(m), function(j) {
            a = row.names(m)[[i]]
            b = row.names(m)[[j]]
    
            do.call(data.frame,
                c(list(a=a, b=b), m[i,] * m[j,])
            )
        })
    )
    

    Sorry part of that looks a little magical -- data.frames aren't really meant to be "row like". The lines

    do.call(data.frame,
        c(list(a=a, b=b), m[i,] * m[j,])
    )
    

    pass in the 6 columns: a and b for the names, concatenated (with c) to the multiplied row.

提交回复
热议问题