I'm trying to divide each number within a data frame with 16 columns by a specific number for each column. The numbers are stored as a data frame with 1-16 corresponding to the samples in the larger data frames columns 1-16. There is a single number per column that I need to divide by each number in the larger spreadsheet and print the output to a final spreadsheet.
Here's and example of what I'm starting with. The spreadsheet to be divided.
X131.478.1 X131.478.2 X131.NSC.1 X131.NSC.2 X166.478.1 X166.478.2
1/2-SBSRNA4 4 2 2 6 7 6
A1BG 93 73 88 86 58 65
A1BG-AS1 123 103 96 128 46 57
The numbers to divide the spreadsheet by
X131.478.1 1.0660880
X131.478.2 0.9104053
X131.NSC.1 0.8642545
X131.NSC.2 0.9611866
X166.478.1 0.9711406
X166.478.2 1.0560121
And the expected results, not necessarily rounded as I did here.
X131.478.1 X131.478.2 X131.NSC.1 X131.NSC.2 X166.478.1 X166.478.2
1/2-SBSRNA4 3.75 2.19 2.31 6.24 7.20 5.68
A1BG 87.23 80.17 101.82 89.47 59.72 61.55
A1BG-AS1 115.37 113.13 111.07 133.16 47.36 53.97
I tried simply dividing the data frames mx2 = mx/sf with mx being the large data set and sf being the data frame of numbers to divide by. That seemed to divide everything by the first number in the sf data set.
The numbers for division were generated by estimateSizeFactors, part of the DESeq package if that helps.
Any help would be great. Thanks!
Just for variety, you could also use
mapply
But for this I think Josh's answer is better... and Gavin's is even better!
You could use
transform
Quite a bit to type with 16 columns, but it should work.
sweep
is useful for these sorts of operations. For example, some dummy data where we divide each element in respective columns of matrixmat
by the corresponding value in the vectorvec
:In use we have:
This is nothing but element-wise matrix multiplication:
To do that we used the outer-product approach, since directly trying
mat %*% 1/vec
gives an error onnon-conformable arguments
because they have different shapes. Or look at the many posts on https://stackoverflow.com/search?q=%5Br%5D+multiply+matrix+by+vector