1

I cannot get around the problem of creating the differentials of every variable (column) in "adat" and saving it to a matrix "dfmtx".

I would just need to automate the following sequence to run for each column in "adat" and than name the obtained vector according to the name of the ones subtracted from each other and placed in to a column of "dfmtx".

In "adat" I have 14 columns and 26 rows not including the header.

dfmtx[,1]=(adat[,1]-adat[,1])
dfmtx[,2]=(adat[,1]-adat[,2])
dfmtx[,3]=(adat[,1]-adat[,3])
dfmtx[,4]=(adat[,1]-adat[,4])
dfmtx[,5]=(adat[,1]-adat[,5])
dfmtx[,6]=(adat[,1]-adat[,6])
.....
dfmtx[,98]=(adat[,14]-adat[,14])

Any help would be appreciated thank you!

smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    @akrun Lower or upper triangle ex the diagonal would have 91 entries, no? – Avraham Jan 28 '15 at 08:33
  • 1
    @Avraham Yes, but in the code showed, the OP already took the diagonal element ie. the first line, which confused me – akrun Jan 28 '15 at 08:34

1 Answers1

6

If adat is a data.frame, you can use outer to get the combinations of columns and then do the difference between pairwise subset of columns based on the index from outer. It is not clear how you got "98" columns. By removing the diagonal and lower triangular elements, the number of columns will be "91".

nm1 <- outer(colnames(adat), colnames(adat), paste, sep="_")
indx1 <-  which(lower.tri(nm1, diag=TRUE))
res <- outer(1:ncol(adat), 1:ncol(adat), 
              function(x,y) adat[,x]-adat[,y])
colnames(res) <- nm1
res1 <- res[-indx1]
dim(res1)
#[1] 26 91

data

set.seed(24)
adat <- as.data.frame(matrix(sample(1:20, 26*14,
                         replace=TRUE), ncol=14))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you it worked great! Now I only have to work mysel around the problem of arranging the names of the original columns subtracted from each other to the new data frame's columns. – Istvan Gabor Hatvani Jan 28 '15 at 08:47
  • Do you happen to have any ideas on that? Thank you very much again. – Istvan Gabor Hatvani Jan 28 '15 at 08:52
  • @IstvanGaborHatvani I changed the code a bit so that the `res1` colnames will be the combination of the names that are involved in the difference – akrun Jan 28 '15 at 08:58
  • the first column of res1 would be named after the first and the second column of "adat" like "A & B". The names of the columns they were created from – Istvan Gabor Hatvani Jan 28 '15 at 08:59
  • @IstvanGaborHatvani My code will be like `A_B`. You can change the `sep` argument in the `nm1` to reflect those changes – akrun Jan 28 '15 at 09:00