计算数据帧中每对列之间的成对差异 [英] Calculate pairwise-difference between each pair of columns in dataframe
问题描述
我无法解决创建adat中每个变量(列)的差异的问题,并将其保存到矩阵dfmtx。
I cannot get around the problem of creating the differentials of every variable (column) in "adat" and saving it to a matrix "dfmtx".
我会只需要自动化以下序列来运行adat中的每一列,而不是按照相应名称的名字命名所获取的矢量,并将其放在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".
在adat中,我有14列和26行不包括标题。
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])
任何帮助将不胜感激
推荐答案
如果 adat
是一个data.frame,你可以使用外部
获取列的组合,然后进行差异下注根据 outer
的索引,将列的成对子集删除。不清楚你如何获得98栏。通过删除对角线和下三角形元素,列数将为91。
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))
这篇关于计算数据帧中每对列之间的成对差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!