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

求助:使用R语言编写年平均气温计算函数的技术问题

Calculate Annual Average Temperatures in R for Your Monthly Data

Hey there! Since you're new to R, let's break this down step by step—no confusing jargon, just straightforward code and explanations to get those 138 annual averages you need.

First, I’ll assume your gistemp.new data frame is structured like this: the first column is Year (from 1880 to 2017), followed by 12 columns for each month’s temperature (e.g., Jan, Feb, ..., Dec). This is the most common setup for yearly/monthly climate data, but if your data looks different, just let me know and we can adjust!

Option 1: Base R (No Extra Packages Needed)

This is perfect for learning the fundamentals without installing new tools. We’ll write a simple function that calculates the mean of each row (each row = one year of monthly temperatures):

# Define the function to compute annual averages
calculate_annual_avg <- function(data) {
  # Grab all monthly temperature columns (exclude the first Year column)
  monthly_temp_data <- data[, -1]
  
  # Calculate the mean for each row (each year), ignoring missing values if any
  annual_averages <- apply(monthly_temp_data, 1, mean, na.rm = TRUE)
  
  # Name the average values with their corresponding years for clarity
  names(annual_averages) <- data[, 1]
  
  return(annual_averages)
}

# Use the function on your dataset
annual_temps <- calculate_annual_avg(gistemp.new)

Quick Breakdown:

  • data[, -1] selects all columns except the first one (your year column).
  • apply(monthly_temp_data, 1, mean, na.rm = TRUE): The 1 tells R to calculate across rows, mean is the function we use, and na.rm = TRUE ensures missing temperature values don’t break the calculation.
  • names(annual_averages) <- data[, 1] adds year labels to your final vector, so you can easily match averages to their corresponding years.

Option 2: Using dplyr (For Tidy Data Workflows)

If you plan to do more data manipulation later, the dplyr package is a game-changer. Here’s how to write a function with it:

First, install and load the package if you haven’t already:

install.packages("dplyr")
library(dplyr)

Then the function:

calculate_annual_avg_tidy <- function(data) {
  data %>%
    # Calculate the mean of all columns except the first (Year)
    summarise(annual_avg = mean(across(-1), na.rm = TRUE)) %>%
    # Extract the averages as a named vector (years as labels)
    pull(annual_avg, name = {{data[[1]]}})
}

# Run the function on your data
annual_temps_tidy <- calculate_annual_avg_tidy(gistemp.new)

Verify Your Result

To make sure you have exactly 138 values (2017 - 1880 + 1 = 138), run this check:

length(annual_temps)

You can also peek at the first few values with head(annual_temps) to ensure they align with your raw monthly data.

If your data is structured differently (e.g., long format where each row is a single month instead of a full year), just shout and we’ll tweak the code!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:07:26