[R] assigning differences in a loop

Marc Schwartz MSchwartz at mn.rr.com
Sun Feb 26 23:04:08 CET 2006


On Sun, 2006-02-26 at 21:47 +0100, Jean-Louis Abitbol wrote:
> Dear All
> 
> I would need to generate differences between variates such as
> nam1<-nam2-nam3 in the following loop:
> 
> 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=".")
>        cat(nam1,"\n")
>        cat(nam2,"\n")
>        cat(nam3,"\n") 
>       }}
> 
> for example the first difference would be dHR13<-HR.13-HR.0
> 
> I have tried
> 
> get(paste("d",j,i,sep=""))<-get(paste(j,i,sep="."))-get(paste(j,"0",sep="."))
> 
> which result in an error message such as "target of the assign does not
> belong to the language" (translation from French).
> 
> I have looked in the FAQ but do not understand how to use assign in this
> context.
> 
> Thanks for any help,

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")

> mat
     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:

> mat[, 2:4] - mat[, 1]
    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




More information about the R-help mailing list