R语言长转宽转换:按规则填充缺失值并正确计算pland差值问题
简化说明
需将长格式数据转换为宽格式,转换规则如下:
- 对2019年字段的缺失值填充为
17,2010年字段的缺失值填充为16 - 当2010年与2019年的landcover值匹配时,按2019年pland值减去2010年pland值计算差值
- 若2019年的值为缺失后填充的
17(原年份无对应记录),则最终pland差值取负;若2010年的值为缺失后填充的16(原年份无对应记录),则最终pland差值保留正值,最终输出结果需符合表2的格式要求。
参考示例
Table 1: 长格式结构的dataframe示例
# A tibble: 10 x 4 year locality_id landcover pland <chr> <chr> <int> <dbl> 1 2010 L452817 8 0.0968 2 2010 L452817 9 0.0323 3 2010 L452817 12 0.613 4 2010 L452817 13 0.194 5 2010 L452817 14 0.0645 6 2019 L452817 8 0.0645 7 2019 L452817 9 0.0645 8 2019 L452817 12 0.516 9 2019 L452817 13 0.194 10 2019 L452817 14 0.161
Table 2: 目标输出的格式要求
locality_id X2010 X2019 pland 1 L452817 8 8 -0.03225806 2 L452817 9 9 0.03225807 3 L452817 12 12 -0.09677420 4 L452817 13 13 0.00000000 5 L452817 14 14 0.09677419 6 L910180 0 17 -0.43750000 7 L910180 8 17 -0.34375000 8 L910180 9 17 -0.03125000 9 L910180 10 17 -0.03125000 10 L910180 11 17 -0.09375000 11 L910180 13 17 -0.06250000
现有实现及问题
已尝试的实现代码
# 将原数据赋值给新变量 y <- t # 移除新变量中的pland列 y <- y[, -4] # 长转宽并尝试计算pland差值 y %>% group_by(year) %>% mutate(row = row_number()) %>% tidyr::pivot_wider(names_from = year, values_from = landcover) %>% select(-row) %>% mutate(across(`2010`:`2019`, ~if(cur_column() == '2019') replace_na(.x, 17) else replace_na(.x, 16))) %>% mutate(pland_diff = t[t$year %in% 2019,]$pland - t[t$year %in% 2010,]$pland) # 现有代码的实际输出 # A tibble: 11 x 4 locality_id `2010` `2019` pland_diff <chr> <dbl> <dbl> <dbl> 1 L452817 8 8 -0.0323 2 L452817 9 9 0.0323 3 L452817 12 12 -0.0968 4 L452817 13 13 0 5 L452817 14 14 0.0968 6 L910180 0 17 -0.373 7 L910180 8 17 -0.279 8 L910180 9 17 0.485 9 L910180 10 17 0.162 10 L910180 11 17 0.0675 11 L910180 13 17 0.00202
核心问题
现有代码始终执行跨行pland差值计算,未对因缺失值填充生成的16、17值做识别处理——当2010或2019列出现填充值16、17时,未按照规则调整差值正负逻辑,出现错配计算,最终输出不符合要求。
可复现原始数据集
structure(list(year = c(2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2019L, 2019L, 2019L, 2019L, 2019L), locality_id = c("L452817", "L452817", "L452817", "L452817", "L452817", "L910180", "L910180", "L910180", "L910180", "L910180", "L910180", "L452817", "L452817", "L452817", "L452817", "L452817" ), landcover = c(8L, 9L, 12L, 13L, 14L, 0L, 8L, 9L, 10L, 11L, 13L, 8L, 9L, 12L, 13L, 14L), pland = c(0.0967741935483871, 0.032258064516129, 0.612903225806452, 0.193548387096774, 0.0645161290322581, 0.4375, 0.34375, 0.03125, 0.03125, 0.09375, 0.0625, 0.0645161290322581, 0.0645161290322581, 0.516129032258065, 0.193548387096774, 0.161290322580645 )), row.names = c(NA, -16L), class = c("tbl_df", "tbl", "data.frame" ))
内容的提问来源于stack exchange,提问作者Lime
相关产品推荐
相关产品推荐

