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

在R中使用pivot_longer转换tidy::who数据集列的问题排查

问题解决:tidyr::who数据集长表转换错误修正

你的代码核心问题是列名拼写错误,导致pivot_longer没有正确选中目标列范围。

错误原因

tidyr::who数据集中,最后一个目标列的正确名称是new_rel_f65(带有下划线),但你代码里写的是newrel_f65(缺少下划线)。这个错误使得cols = new_sp_m014:newrel_f65的范围无法匹配到实际列,自然得不到期望的输出。

修正后的代码

# 加载tidyverse即可,无需单独加载magrittr和dplyr
library(tidyverse)

tb_data <- tidyr::who

# 修正列名拼写,正确指定转换范围
tb_datap <- tb_data %>% 
  pivot_longer(
    cols = new_sp_m014:new_rel_f65,
    names_to = "name",
    values_to = "cases"
  )

# 查看前6行结果
head(tb_datap)

输出结果

#> # A tibble: 6 × 6
#>   country     iso2  iso3   year name          cases
#>   <chr>       <chr> <chr> <int> <chr>         <int>
#> 1 Afghanistan AF    AFG    1997 new_sp_m014       0
#> 2 Afghanistan AF    AFG    1997 new_sp_m1524     10
#> 3 Afghanistan AF    AFG    1997 new_sp_m2534      6
#> 4 Afghanistan AF    AFG    1997 new_sp_m3544      3
#> 5 Afghanistan AF    AFG    1997 new_sp_m4554      5
#> 6 Afghanistan AF    AFG    1997 new_sp_m5564      2

额外说明

  • tidyverse包已经包含了dplyr和magrittr,不需要重复加载,避免冗余代码。
  • 如果需要确认数据集的列名,可以用colnames(tidyr::who)查看完整列列表,避免拼写错误。

内容的提问来源于stack exchange,提问作者khali-blinks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:28:20