R语言分析冬小麦生长数据:获取每个年份和年份+1的结果
{/n/'title/': /'R语言分析冬小麦生长数据:获取每个年份和年份+1的结果/',/n/'description/': /'本代码使用R语言分析冬小麦生长数据,提取每个年份和年份+1的生长季数据,计算平均气温、总降雨量和成熟时的产量,并将其保存到CSV文件中。/',/n/'keywords/': /'冬小麦, 生长数据, R语言, dplyr, 生长季, 平均气温, 总降雨量, 成熟产量, CSV/',/n/'content/': /'///'library(dplyr)//nlibrary(tools)//n//n# 读取数据文件//ndf //u003c- fread(///'E:/trainingdata/wheatOUTfile/75csv/Hebei_bazhou.csv///')//n//n# 提取冬小麦生长季数据//nwinter_wheat //u003c- df //u003e//%//n filter(StageName //u003c- %in% c(///'sowing///', ///'maturity///'))//n//n# 提取起始年份和结束年份//nstart_year //u003c- 1981//nend_year //u003c- 2011//n//n# 创建空的结果列表//nresults //u003c- list()//n//n# 循环处理每个年份范围//nfor (year in start_year:end_year) {//n # 调整年份对应的播种和成熟年份//n planting_year //u003c- year//n maturity_year //u003c- year + 1//n //n # 提取当前年份范围内的数据//n data_filtered //u003c- winter_wheat //u003e//%//n filter(year //u003e= planting_year & year //u003c= maturity_year)//n //n # 计算指标//n result //u003c- data_filtered //u003e//%//n summarise(//n Avg_Temperature = mean(MaxT),//n Total_Rainfall = sum(Rain)//n )//n //n # 提取成熟时的产量//n yield_at_maturity //u003c- df //u003e//%//n filter(year == maturity_year, StageName == ///'maturity///') //u003e//%//n select(yield)//n //n # 检查成熟阶段的产量是否存在//n if (nrow(yield_at_maturity) //u003e 0) {//n result$Yield_at_Maturity //u003c- yield_at_maturity$yield//n } else {//n result$Yield_at_Maturity //u003c- NA # 或其他合适的值//n }//n //n # 添加年份和文件名列//n result$Year //u003c- planting_year//n result$File_Name //u003c- basename(file_path_sans_ext(///'E:/trainingdata/wheatOUTfile/75csv/Hebei_bazhou.csv///'))//n //n # 将结果添加到结果数据框中//n results //u003c- bind_rows(results, result)//n //n # 将结果保存到CSV文件//n output_file //u003c- paste0(///'output_///', planting_year, ///'-///', maturity_year, ///'.csv///')//n write.csv(result, file = output_file, row.names = FALSE)//n}//n//n#将所有结果合并为一个数据框//ncombined_results //u003c- bind_rows(results)//n//n# 将结果保存到CSV文件//nwrite.csv(combined_results, file = ///'E:/trainingdata/wheatOUTfile/75csv/Hebei_bazhou_combined.csv///', row.names = FALSE)/
原文地址: https://www.cveoy.top/t/topic/pC1A 著作权归作者所有。请勿转载和采集!