0

我很困惑为什么会发生这个错误。我正在尝试编写一个将字符串传递给包的函数,get_decennial()tidycensus它会引发错误。

我能够在函数范围之外成功运行相同的代码。我似乎无法理解为什么将输入传递给函数会使其失败。特别是,因为我已经成功地将一个对象传递给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(key)), value_col = compat_as_lazy(enquo(value)) 中重新运行时出现调试错误,: 未使用的参数 (-NAME)”

4

1 回答 1

4

因为 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!
于 2018-06-25T22:41:39.147 回答