使用R语言dplyr包的pivot_wider实现多列数据重排
数据集重排解决方案:先转长表再转宽表
要实现你想要的数据集结构转换,不能直接用pivot_wider,得先把宽格式的物种列转为长格式,再重新调整KUD为列。以下是具体实现步骤:
1. 加载必要的包
library(tidyverse)
2. 导入可复现数据集
df <- structure(list(Grey.Reef.Shark = c(0.0153693415007032, 0.0743482431216283, 0.0157723122886768, 0.0718452019326124, 0.0271587991640831, 0.139118848810864 ), Silvertip.Shark = c(0.00616969268071902, 0.0677936053733444, 0.00983240322136223, 0.0926378231217502, 0.0484117524071891, 0.235938189749556), monthyear = c("2014/01", "2014/01", "2014/02", "2014/02", "2014/03", "2014/03"), KUD = structure(c(1L, 2L, 1L, 2L, 1L, 2L), levels = c("50", "95"), class = "factor")), row.names = c("50", "95", "501", "951", "502", "952"), class = "data.frame")
3. 执行数据转换
核心是两步:先用pivot_longer把两个鲨鱼物种列合并为species和value列,再用pivot_wider把KUD的不同取值转为列:
result <- df %>% # 将物种列转为长格式 pivot_longer(cols = c(Grey.Reef.Shark, Silvertip.Shark), names_to = "species", values_to = "value") %>% # 将KUD转为宽格式列 pivot_wider(names_from = KUD, values_from = value) %>% # 调整列顺序匹配期望格式 select(`50`, `95`, monthyear, species)
4. 查看转换结果
运行上述代码后,输出结果与你期望的格式一致:
print(result) #> # A tibble: 6 × 4 #> `50` `95` monthyear species #> <dbl> <dbl> <chr> <chr> #> 1 0.0154 0.0743 2014/01 Grey.Reef.Shark #> 2 0.00617 0.0678 2014/01 Silvertip.Shark #> 3 0.0158 0.0718 2014/02 Grey.Reef.Shark #> 4 0.00983 0.0926 2014/02 Silvertip.Shark #> 5 0.0272 0.139 2014/03 Grey.Reef.Shark #> 6 0.0484 0.236 2014/03 Silvertip.Shark
内容的提问来源于stack exchange,提问作者mikejwilliamson
相关产品推荐
相关产品推荐

