wbstats弃用函数报错与dcast警告修复及tidyr替代方案求助
解决方案
问题说明
你遇到的所有报错和警告均来自依赖包的版本迭代接口变更:
wb()函数在wbstats 1.0及以上版本已被弃用,新版wb_data()返回的数据结构和旧版完全不同,不再默认提供value、indicatorID列,所以直接替换函数名后mutate操作不存在的列会触发报错- data.table::dcast对data.frame类型输入的兼容重定向功能已被弃用,reshape2包也已停止维护,推荐使用tidyverse生态的
tidyr::pivot_wider()实现长表转宽表需求
可行实现代码
方案一:推荐写法(更简洁高效)
一次性拉取所有指标后直接清洗,不需要多次接口请求再合并:
library(tidyverse) library(wbstats) # 批量拉取3个所需指标,自定义别名 raw_wb_data <- wb_data( indicator = c( "SP.POP.TOTL" = "Population", "NY.GDP.PCAP.CD" = "GDP per Capita", "SP.DYN.LE00.IN" = "Life Expectancy" ), country = "countries_only" ) # 数据清洗得到最终宽表 df <- raw_wb_data %>% mutate( date = as.numeric(date), # 人口单位转换为百万,保留2位小数 Population = round(Population / 1e6, 2), `GDP per Capita` = round(`GDP per Capita`, 2), `Life Expectancy` = round(`Life Expectancy`, 2) ) %>% na.omit()
方案二:对齐原代码逻辑的写法
完全沿用你原来分开拉取、合并后转宽表的开发逻辑,便于对应理解:
library(tidyverse) library(wbstats) # 封装统一的指标拉取函数,减少重复代码 pull_wb_indicator <- function(ind_code, ind_name, value_process = ~round(.x, 2)) { wb_data(indicator = ind_code, country = "countries_only") %>% # 将指标列重命名为统一的value列,适配原逻辑 rename(value = all_of(ind_code)) %>% mutate( date = as.numeric(date), value = rlang::exec(value_process, value), indicator = ind_name ) %>% # 保留和旧版wb()输出一致的通用字段 select(iso2c, iso3c, country, date, value, indicator) } # 分别拉取三个指标 population <- pull_wb_indicator("SP.POP.TOTL", "Population", ~round(.x / 1e6, 2)) gdp <- pull_wb_indicator("NY.GDP.PCAP.CD", "GDP per Capita") lifeexpectancy <- pull_wb_indicator("SP.DYN.LE00.IN", "Life Expectancy") # 合并后用tidyr::pivot_wider转宽表,无弃用警告 df <- gdp %>% rbind(lifeexpectancy) %>% rbind(population) %>% pivot_wider(names_from = indicator, values_from = value) %>% na.omit()
两种方案输出的最终数据框和你原代码预期的结构完全一致。
内容的提问来源于stack exchange,提问作者gab77777
相关产品推荐
相关产品推荐

