使用mutate计算表格的6列之间的所有绝对差值? [英] Calculate all the absolute differences between 6 columns of a table using mutate?
问题描述
我有一个包含6列Z1到Z6列的表,我想计算这些列之间的差的绝对值.
I have a table with 6 columns Z1 to Z6, and I want to calculate the absolute value of the difference between each of these columns.
到目前为止,我列举了mutate命令中的所有差异:
So far, I enumerate all the differences in a mutate command:
FactArray <- FactArray %>% mutate(diff12 = abs(Z1-Z2),
diff13 = abs(Z1-Z3),
diff14 = abs(Z1-Z4),
diff15 = abs(Z1-Z5),
diff16 = abs(Z1-Z6),
diff23 = abs(Z2-Z3),
diff24 = abs(Z2-Z4),
diff25 = abs(Z2-Z5),
diff26 = abs(Z2-Z6),
diff34 = abs(Z3-Z4),
diff35 = abs(Z3-Z5),
diff36 = abs(Z3-Z6),
diff46 = abs(Z4-Z6),
diff56 = abs(Z5-Z6))
但是我意识到这很容易出错,如果我的列数不同,则必须重写.
But I realise this is error prone and will have to be rewritten if I have a different number of columns.
有什么方法可以自动"执行此操作?我的意思是,如果我考虑任意数量的列,它会自行调整?
Is there any way to do this "automatically"? I mean in a way such as it would adjust itself if I am considering any number of columns?
最好
达明(Damien)
推荐答案
您可以使用 combn
生成所有可能的列组合,然后减去它们.
You can generate all possible combination of the columns using combn
and subtract them.
cols <- paste0('Z', 1:6)
combn(cols, 2, function(x) abs(df[[x[1]]] - df[[x[2]]]))
这里使用的是一个小的可复制示例,还添加了适当的列名.
Here's using a small reproducible example also adding appropriate column names.
set.seed(123)
df <- data.frame(Z1 = sample(10, 4), Z2 = sample(10, 4), Z3 = sample(10,4))
cols <- paste0('Z', 1:3)
new_cols <- combn(cols, 2, paste0, collapse = "_")
df[new_cols] <- combn(cols, 2, function(x) abs(df[[x[1]]] - df[[x[2]]]))
df
# Z1 Z2 Z3 Z1_Z2 Z1_Z3 Z2_Z3
#1 3 6 6 3 3 0
#2 10 5 9 5 1 4
#3 2 4 2 2 0 2
#4 8 10 3 2 5 7
这篇关于使用mutate计算表格的6列之间的所有绝对差值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!