1
votes

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!

1
@akrun Lower or upper triangle ex the diagonal would have 91 entries, no? - Avraham
@Avraham Yes, but in the code showed, the OP already took the diagonal element ie. the first line, which confused me - akrun

1 Answers

6
votes

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