首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么在函数中使用tidycensus get_decennial()会失败?

为什么在函数中使用tidycensus get_decennial()会失败?
EN

Stack Overflow用户
提问于 2018-06-26 06:06:21
回答 1查看 626关注 0票数 0

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

我能够成功地在函数的作用域之外运行相同的代码。我似乎不明白为什么向函数传递一个输入会导致它失败。尤其是,因为我已经成功地将一个对象传递给了county参数的函数(如下所示)。其他人有没有遇到过这样的事情?我认为下面的例子说明了这个问题。我尝试复制上一次调用的输出/错误,但我提前为低质量的格式表示道歉。

代码语言:javascript
复制
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))中的调试错误

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-26 06:41:39

这是因为R沿着环境层次结构评估对象的方式。换句话说,在get_decennial()函数的代码中已经有一个名为"x“的元素。您的自定义函数why_doesnt_this_work()的计算级别与get_decennial()相同。因此,至少有两个元素/对象的相同值被应用于get_decennial管道,从而破坏了一些东西。

要解决这个问题,只需将您的自定义x重命名为get_decennial期望的名称,即“状态”。

代码语言:javascript
复制
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!
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51032407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档