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,0,1,0), D=c(1,1,1,1))
A B C D
w 0 0 1 1
x 0 1 0 1
y 0 0 1 1
z 0 0 0 1
I want to apply an equation i.e. multiply row w to row x to get the pairwise value for w-x pair, as follows:
A B C D
w 0 0 1 1
X x 0 1 0 1
--------------
wx 0 0 0 1
to get row-wise analysis for w-x, w-y, w-y, w-z, x-y, x-z, y-z. and generate a new dataframe with 6 columns (two row names followed by the multiplied values).
That's
w x 0 0 0 1
w y 0 0 1 1
w z 0 0 0 1
x y 0 0 0 1
x z 0 0 0 1
y z 0 0 0 1
Thanksssssss.
So the final solution:
If you convert the combos to a dataframe you would also be able to cbindmatrix as type "numeric":
A shorter way (I think) using the amazing plyr package
Your data.frame
And your result :)
If you don't want the combo names in the resulting object, then we can combine elements of @DWin's and @Owen's Answers to provide a truly vectorised approach to the problem. (You can add the combination names as row names with one extra step at the end.)
First, the data:
Take the
combn()
idea from @DWin's Answer but use it on the row indices ofdat
:The rows of
combs
now index the rows ofdat
that we want to multiply together:Now we take the idea @Owen showed, namely
dat[i, ] * dat[j, ]
withi
andj
being the first and second rows ofcombs
respectively. We convert to a matrix withdata.matrix()
as this will be more efficient for large objects, but the code will work withdat
as a data frame too.which produces:
To see how this works, note that
mat[combs[k,], ]
produces a matrix with various rows repeated in the order specified by the combinations:To get exactly what the OP posted, we can modify the rownames using a second
combn()
call:If you want to multiply rows, I recommend converting to a matrix:
The specific result you want you could get with
plyr
,Sorry part of that looks a little magical -- data.frames aren't really meant to be "row like". The lines
pass in the 6 columns: a and b for the names, concatenated (with
c
) to the multiplied row.