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

如何在R语言中赋值向量并按身高升序对姓名向量排序?

按身高升序排序姓名的R实现

修复原冒泡排序代码

原代码存在一处拼写错误:heights[I]中的大写I需改为小写i,同时可以优化循环逻辑减少不必要的遍历。修复后的代码如下:

heights = c(154,152,165,160)
names(heights) = c("Dan","Gan","Tan","Ban")

n = length(heights)
# 外层循环只需执行n-1次即可完成排序
for(j in c(1:(n-1))) {
  # 内层循环跳过已排序的尾部元素,提升效率
  for(i in c(1:(n-j))) {
    if(heights[i] > heights[i+1]) {
      c = heights[i]
      heights[i] = heights[i+1]
      heights[i+1] = c
    }
  }
}
print(heights)

运行后会输出按身高升序排列的向量,其中姓名就是排序后的结果:

Gan  Dan  Ban  Tan 
 152  154  160  165 

更简洁的R内置函数实现

R自带高效的排序工具,无需手动编写冒泡排序,以下两种方法更实用:

方法1:直接排序带姓名的身高向量

heights = c(154,152,165,160)
names(heights) = c("Dan","Gan","Tan","Ban")

# 按身高升序排序,直接返回关联姓名的结果
sorted_heights = sort(heights, decreasing = FALSE)
# 提取排序后的姓名列表
sorted_names = names(sorted_heights)
print(sorted_names)

输出:

[1] "Gan" "Dan" "Ban" "Tan"

方法2:用order()获取排序索引提取姓名

heights = c(154,152,165,160)
names = c("Dan","Gan","Tan","Ban")

# 获取按身高升序排列的元素索引
sorted_indices = order(heights)
# 根据索引提取对应姓名
sorted_names = names[sorted_indices]
print(sorted_names)

输出同样为:

[1] "Gan" "Dan" "Ban" "Tan"

内容的提问来源于stack exchange,提问作者collegekid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:05:27