从州名和县名到 R 中的 fips

From state and county names to fips in R

我在 R 中有以下数据框。我想从这个数据集中获取 fips。我尝试在 usmap (https://rdrr.io/cran/usmap/man/fips.html) 中使用 fips 函数。但是我无法从这个函数中得到 fips,因为我需要用双引号引起来。然后,我尝试使用paste0(""", df$state, """),但我无法获取它。有什么有效的方法可以得到fips吗?

> df1
                   state           county
1             california             napa
2                florida       palm beach
3                florida          collier
4                florida            duval

更新

我可以用dQuote得到"\"california\""。谢谢。每列转换后,我尝试了以下操作。我该如何处理这个问题?

> df1$state <- dQuote(df1$state, FALSE)
> df1$county <- dQuote(df1$county, FALSE)
> fips(state = df1$state, county = df1$county)
Error in fips(state = df1$state, county = df1$county) : 
  `county` parameter cannot be used with multiple states.

> fips(state = df1$state[1], county = df1$county[1])
Error in fips(state = df1$state[1], county = df1$county[1]) : 
  "napa" is not a valid county in "california".

> fips(state = "california", county = "napa")
[1] "06055"

我们可以通过 state split 数据集并应用 fips

library(usmap)
lapply(split(df1, df1$state), function(x)
      fips(state = x$state[1], county = x$county))
#$california
#[1] "06055"

#$florida
#[1] "12099" "12021" "12031"

Map

lst1 <- split(df1$county, df1$state)
Map(fips, lst1, state = names(lst1))
#$california
#[1] "06055"

#$florida
#[1] "12099" "12021" "12031"

tidyverse

library(dplyr)
library(tidyr)
df1 %>% 
    group_by(state) %>% 
    summarise(new = list(fips(state = first(state), county = county))) %>%
    unnest(c(new))
# A tibble: 4 x 2
#  state      new  
#  <chr>      <chr>
#1 california 06055
#2 florida    12099
#3 florida    12021
#4 florida    12031

数据

df1 <- structure(list(state = c("california", "florida", "florida", 
"florida"), county = c("napa", "palm beach", "collier", "duval"
)), class = "data.frame", row.names = c("1", "2", "3", "4"))