如何在R语言中按方差降序排列数据集的列?
按列方差降序排列数据集列的解决方案
你之前的代码失效是因为sort()返回的是排序后的方差数值,而数据框取列需要的是列的索引位置。要实现目标,应该用order()函数——它会返回能让方差向量降序排列的列索引,用这个索引取列就能完成排序。
一行代码实现
og_data_sorted <- og_data[, order(apply(og_data, 2, var), decreasing = TRUE)]
分步拆解(更易理解)
- 先计算每一列的方差:
col_variances <- apply(og_data, 2, var)
- 获取按方差降序排列的列索引:
sorted_col_indices <- order(col_variances, decreasing = TRUE)
- 用索引重新排列数据集:
og_data_sorted <- og_data[, sorted_col_indices]
处理完成后,og_data_sorted就是列按方差从高到低排列后的数据集。
内容的提问来源于stack exchange,提问作者wantingtoimprove
相关产品推荐
相关产品推荐

