我很困惑为什么会发生这个错误。我正在尝试编写一个函数,该函数将字符串从tidycensus
包传递给get_decennial()
,但它抛出了一个错误。
我能够成功地在函数的作用域之外运行相同的代码。我似乎不明白为什么向函数传递一个输入会导致它失败。尤其是,因为我已经成功地将一个对象传递给了county
参数的函数(如下所示)。其他人有没有遇到过这样的事情?我认为下面的例子说明了这个问题。我尝试复制上一次调用的输出/错误,但我提前为低质量的格式表示道歉。
library(tidycensus)
library(dplyr)
census_api_key(Sys.getenv("CENSUS_API_KEY")) # put your census api key here
oregon <- filter(fips_codes, state_name == "Oregon")
oregon_counties <- oregon$county_code
# this works
why_does_this_work <- "Oregon"
get_decennial(geography = "block group",
state = why_does_this_work,
variables = "H00010001",
county = oregon_counties,
quiet = TRUE)
# why doesn't this work
why_doesnt_this_work <- function(x) {
get_decennial(geography = "block group",
state = x,
variables = "H00010001",
county = oregon_counties,
quiet = TRUE)
}
why_doesnt_this_work("Oregon")
Getting data from the 2010 decennial Census
Getting data from the 2010 decennial Census
Getting data from the 2010 decennial Census
Error : Result 1 is not a length 1 atomic vector
In addition: Warning messages:
1: '03' is not a valid FIPS code or state name/abbreviation
2: '03' is not a valid FIPS code or state name/abbreviation
“显示回溯
重新运行时出现gather_(data,key_col =compat_as_lazy(enquo(键)),value_col =compat_as_lazy(enquo(值)),:未使用的参数(-NAME))中的调试错误
发布于 2018-06-26 06:41:39
这是因为R沿着环境层次结构评估对象的方式。换句话说,在get_decennial()函数的代码中已经有一个名为"x“的元素。您的自定义函数why_doesnt_this_work()的计算级别与get_decennial()相同。因此,至少有两个元素/对象的相同值被应用于get_decennial管道,从而破坏了一些东西。
要解决这个问题,只需将您的自定义x重命名为get_decennial期望的名称,即“状态”。
why_doesnt_this_work <- function(state) {
get_decennial(geography = "block group",
state = as.character(state),
variables = "H00010001",
county = oregon_counties,
quiet = TRUE)
}
why_doesnt_this_work('Oregon') ## Now it works!
https://stackoverflow.com/questions/51032407
复制相似问题