Skip to content
Prev 87253 / 398513 Next

assigning differences in a loop

On Sun, 2006-02-26 at 21:47 +0100, Jean-Louis Abitbol wrote:
Presumably, the error is referring to the fact that the target of the
subtraction operation does not yet exist. Thus, get() is returning an
error.

Lacking your data, which I presume is ECG measurement information from
the acronyms in use, you could do something like this:

for(i in c("13","26","38")) { 
    for (j in c("HR","PQ","QRS","QT")){
       nam1<-paste("d",j,i,sep="")
       nam2<-paste(j,i,sep=".")
       nam3<-paste(j,"0",sep=".")
       eval(parse(text = paste(nam1, " <- ", nam2, " - ", nam3,  "\n")))
      }}

Note that the result of the last line in the loop is a series of
expressions, which are then evaluated:

  expression(dHR13 <- HR.13 - HR.0)
  expression(dPQ13 <- PQ.13 - PQ.0)
  expression(dQRS13 <- QRS.13 - QRS.0)
  expression(dQT13 <- QT.13 - QT.0)
  expression(dHR26 <- HR.26 - HR.0)
  expression(dPQ26 <- PQ.26 - PQ.0)
  expression(dQRS26 <- QRS.26 - QRS.0)
  expression(dQT26 <- QT.26 - QT.0)
  expression(dHR38 <- HR.38 - HR.0)
  expression(dPQ38 <- PQ.38 - PQ.0)
  expression(dQRS38 <- QRS.38 - QRS.0)
  expression(dQT38 <- QT.38 - QT.0)

You can see this if you replace that last line with:

  print(parse(text = paste(nam1, " <- ", nam2, " - ", nam3,  "\n")))


However, I can't help but think that there is an easier way here. If
your data might be in a matrix 'mat' (or could be put into this format),
with the following example structure:

set.seed(1)
mat <- matrix(sample(16), 4, 4)
colnames(mat) <- c("0", "13","26","38")
rownames(mat) <- c("HR","PQ","QRS","QT")
0 13 26 38
HR   5  3 14 13
PQ   6 10  1  8
QRS  9 11  2  4
QT  12 15  7 16


You can then use:
13 26 38
HR  -2  9  8
PQ   4 -5  2
QRS  2 -7 -5
QT   3 -5  4


which creates a matrix with the results of subtracting cols 2:4 from col
1.

HTH,

Marc Schwartz