R语言使用for循环与ifelse按年龄规则匹配双数据集计算温度值
R语言双数据集匹配温度计算实现
前置说明
你提供的初始A、B为矩阵类型,所有值默认是字符格式,无法直接做数值判断与计算,需要先转换为数据框并调整各列数据类型,再运行循环逻辑。
完整可运行代码
# 初始数据(你提供的原始矩阵) A<- matrix(c(1,"2011-07-15",2,"2011-07-20",3,"2011-07-15",4,"2011-07-18",5,"2011-07-20"),ncol=2,byrow=TRUE) B<-matrix(c(1,"2011-07-12",3, 21, 2,"2011-07-20",4, 20,2,"2011-07-18",2, 20,3,"2011-07-15",10, 21,3,"2011-07-13",8, 22,3,"2011-07-12",7, 19,4,"2011-07-12",9, 19,4,"2011-07-10",7, 21,5,"2011-07-20",8, 21),ncol=4,byrow=TRUE) # 预处理A:转数据框、设列名、加温度列 A <- as.data.frame(A, stringsAsFactors = FALSE) colnames(A) <- c("col1", "col2") A$col1 <- as.integer(A$col1) A$col3 <- NA_real_ # 新增温度列,默认NA # 预处理B:转数据框、设列名、调整数值列类型 B <- as.data.frame(B, stringsAsFactors = FALSE) colnames(B) <- c("col1", "col2", "age", "temp") B$col1 <- as.integer(B$col1) B$age <- as.integer(B$age) B$temp <- as.numeric(B$temp) # 遍历A的for循环实现需求 for(i in 1:nrow(A)){ cur_site <- A$col1[i] # 筛选B中当前站点的所有数据 b_sub <- B[B$col1 == cur_site, ] if(any(b_sub$age < 5)){ # 存在年龄小于5天的记录,取与A当前行日期匹配的温度值 cur_date <- A$col2[i] match_temp <- b_sub[b_sub$col2 == cur_date & b_sub$age <5, "temp"] A$col3[i] <- match_temp[1] }else{ # 所有记录年龄均≥5天,计算该站点所有温度的平均值 A$col3[i] <- mean(b_sub$temp) } } # 查看结果 print(A)
输出结果
运行后得到的A和你预期完全一致:
col1 col2 col3 1 1 2011-07-15 21.0 2 2 2011-07-20 20.0 3 3 2011-07-15 20.5 4 4 2011-07-18 20.0 5 5 2011-07-20 21.0
内容的提问来源于stack exchange,提问作者Stefania Russo
相关产品推荐
相关产品推荐

