1

I have a data object signal in R with 40,000+ rows (named variables) of numeric values and 200+ columns (samples). For every row of each column, I want to subtract the value for the row named background for that column.

The code below can be used to create an example signal object in R. With the example, for column A, the background value of 4 is to be subtracted from the values of channelNo1 to 3. Similarly, for column B, the value of 6 is to be subtracted. And so on. What is the simplest way to achieve this in R?

text <- textConnection('
             A   B   C
channelNo1  12  22  32
channelNo2  13  21  33
channelNo3  12  21  30
background   4   6   8
')
signal <- read.table(text, header = TRUE)
close(text)

typeof(signal)
# returns 'list'

class(signal)
# returns 'data.frame'
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user594694
  • 327
  • 4
  • 13
  • 3
    Try providing a small [reproducible](http://stackoverflow.com/q/5963269/324364) example that others can use to demonstrate an answer. – joran May 26 '12 at 04:22
  • 2
    Just a note but you have the data back to front as far as most of R is concerned. Rows are samples/observations, columns are the variables. – Gavin Simpson May 26 '12 at 09:13

1 Answers1

2

Elements in an R matrix are oriented by column (check out matrix(1:12, nrow=3) and signal - signal[4,] is not doing what you think -- check out column B, where the second and third values should be the same (and equal to 15). You could write

as.data.frame(Map("-", signal, as.vector(signal[4,])))

(I think this would be relatively efficient) but since the data really seem to be a matrix (i.e., a rectangle of homogeneous type) it makes a lot more sense to manipulate it as a matrix

m = as.matrix(signal)
sweep(m, 2, m[4,], "-")
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • Both of your suggestions work. Thank you, and also for pointing out the incorrectness I had in the example code. I have removed it. – user594694 May 27 '12 at 01:43