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

新手编程求助:理解R语言求温度最大值代码及手动实现极值均值函数

这段R语言求温度最大值代码的逐行解释

1. 读取温度输入

这部分代码用于逐个获取10个城市的温度手动输入:

A1 <- as.numeric(readline(prompt = "Write the temperature for Tokyo: "))
B2 <- as.numeric(readline(prompt = "Write the temperature for Johannesburg: "))
C3 <- as.numeric(readline(prompt = "Write the temperature for Stockholm: "))
D4 <- as.numeric(readline(prompt = "Write the temperature for Oslo: "))
E5 <- as.numeric(readline(prompt = "Write the temperature for Amsterdam: "))
F6 <- as.numeric(readline(prompt = "Write the temperature for Mexico city: "))
G7 <- as.numeric(readline(prompt = "Write the temperature for Hanoi: "))
H8 <- as.numeric(readline(prompt = "Write the temperature for Canberra: "))
I9 <- as.numeric(readline(prompt = "Write the temperature for Tbilisi: "))
J10 <- as.numeric(readline(prompt = "Write the temperature for New Delhi: "))
  • readline(prompt = "..."):弹出提示文本,让用户输入对应城市的温度,输入内容默认是字符串类型。
  • as.numeric():把输入的字符串转换成数值类型,保证后续能进行数值比较运算。
  • 每个变量(A1到J10)分别存储一个城市的温度值。

2. 数据格式转换

data = data.frame(A1,B2,C3,D4,E5,F6,G7,H8,I9,J10)
datamatrix <- as.matrix(data) #Converts data into a matrix
  • data.frame():将10个温度变量打包成表格形式的数据框。
  • as.matrix(data):把数据框转换成矩阵格式,方便后续循环遍历元素。但这一步属于冗余操作,直接遍历数据框的元素也能实现需求。

3. 循环求最大值的核心逻辑

y=-Inf
z=0
for(i in datamatrix) {
  
  if(i>y){
    y=i
    
    if(y!=Inf){z=i}
  }
  else{y=Inf}
}
print(paste0("maximum number is: ", z))

这部分是代码的核心,但存在逻辑冗余与错误,逐行拆解:

  • 初始化变量:
    • y=-Inf:将y设为负无穷,确保第一个输入的温度必然大于它,能触发第一次更新。
    • z=0:用来存储最终找到的最大值,初始值设为0。
  • for(i in datamatrix):逐个取出矩阵中的每个温度值,赋值给变量i。
  • 内部判断逻辑:
    1. 当当前温度i大于y时:
      • 更新y为当前温度i,此时y代表目前遍历过的最大值。
      • 判断y不等于无穷大(此判断完全多余,因为输入的温度不可能是无穷大),随后将z也更新为i。
    2. 当当前温度i不大于y时:
      • 将y设为正无穷,这是逻辑错误。比如输入温度序列为20,15,25,第一个温度20会让y=20、z=20;第二个温度15小于20,y被设为正无穷;第三个温度25小于正无穷,z无法更新为25,最终结果会漏掉真正的最大值。
  • print(paste0("maximum number is: ", z)):将结果拼接成字符串并打印输出。

代码的问题与优化方向

  • 变量命名混乱:A1、B2这类命名无意义,换成tokyo_temp、johannesburg_temp会更清晰易懂。
  • 冗余格式转换:无需将数据框转为矩阵,直接用for(i in data)即可遍历所有温度值。
  • 循环逻辑错误:遇到更小值时将y设为正无穷,会导致后续无法正确识别更大的数值。
  • 更简洁的实现:R自带max()函数,直接调用max(A1,B2,C3,D4,E5,F6,G7,H8,I9,J10)就能得到最大值,完全不需要手动写循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:55:20