gpt4 book ai didi

r - bind_rows(),列不能从整数转换为字符错误

转载 作者:行者123 更新时间:2023-12-04 01:32:32 24 4
gpt4 key购买 nike

我看过这个答案:Error in bind_rows_(x, .id) : Column can't be converted from factor to numeric但我不能mutate_all()一个列表。

library(rvest)
library(dplyr)
library(tidyr)

fips <- read_html("https://www.census.gov/geo/reference/ansi_statetables.html") %>%
html_nodes("table") %>%
html_table() %>%
bind_rows(.[[1]][1:3] %>%
transmute(name = `Name`,
fips = as.character(`FIPS State Numeric Code`),
abb = `Official USPS Code`),
filter(.[[2]][1:3], !grepl("Status",c(`Area Name`))) %>%
transmute(name = `Area Name`,
fips = as.character(`FIPS State Numeric Code`),
abb = `Official USPS Code`))

Error in bind_rows_(list_or_dots(...), id = NULL) :
Column `FIPS State Numeric Code` can't be converted from integer to character

然而,这段代码工作得很好:
fips <- read_html("https://www.census.gov/geo/reference/ansi_statetables.html")

dat3 <- fips %>%
html_nodes("table") %>%
html_table()

rbind(dat3[[1]][1:3] %>%
transmute(name = `Name`,
fips = `FIPS State Numeric Code`,
abb = `Official USPS Code`),
filter(dat3[[2]][1:3], !grepl("Status",c(`Area Name`))) %>%
transmute(name = `Area Name`,
fips = `FIPS State Numeric Code`,
abb = `Official USPS Code`))

最佳答案

正如@akrun 在评论中指出的, bind_rows 是类型敏感的。因此,我会首先使用 lapply在 dplyr 内到 mutate_if在列表中,然后 bind_rows字符数据帧,setNames能够调用 filter 中的变量在最后一步中通过 Area_Name 进行操作:

fips <- read_html("https://www.census.gov/geo/reference/ansi_statetables.html") %>% 
html_nodes("table") %>%
html_table() %>%
lapply(., mutate_if, is.integer, as.character) %>%
bind_rows() %>%
setNames(gsub(" ", "_", names(.))) %>%
filter(!grepl("Status", Area_Name)) %>%
mutate(Name = ifelse(is.na(Name), Area_Name, Name)) %>%
select(Name, FIPS_State_Numeric_Code, Official_USPS_Code)

关于r - bind_rows(),列不能从整数转换为字符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com