You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:05:33