I have a data.table
containing some state name abbreviations and county names. I want to get approx. coordinates from ggplot2::map_data('county')
for each row.
I can do this sequentially with multiple lines of code using :=
but I would like to make only one function call.
Below is what I've tried:
Data:
library(data.table)
library(ggplot2)
> dput(dt[1:20, .(state, county, prime_mover)])
structure(list(state = c("AZ", "AZ", "CA", "CA", "CA", "CT",
"FL", "IN", "MA", "MA", "MA", "MN", "NJ", "NJ", "NJ", "NY", "NC",
"SC", "TN", "TX"), county = c("Maricopa", "Maricopa", "Los Angeles",
"Orange", "Los Angeles", "Fairfield", "Hillsborough", "Morgan",
"Barnstable", "Nantucket", "Essex", "Dakota", "Cape May", "Salem",
"Middlesex", "Kings", "Buncombe", "Anderson", "Shelby", "Tarrant"
), prime_mover = c("GT", "GT", "CT", "CT", "CT", "CT", "GT",
"CT", "GT", "GT", "GT", "GT", "CT", "GT", "CT", "GT", "CT", "CT",
"CT", "CT")), .Names = c("state", "county", "prime_mover"), row.names = c(NA,
-20L), class = c("data.table", "data.frame"))
coord_data <- as.data.table(map_data('county'))
CODE:
getCoords <- function(state, county){
prov <- state.name[grep(state, state.abb)]
ck <- coord_data[region == tolower(prov) & subregion == tolower(county),
.(lon = mean(long), lat = mean(lat))]
return(list(unname(unlist(ck))))
}
# Testing getCoords
> getCoords('AZ', 'Maricopa')
[[1]]
[1] -111.88668 33.58126
ERRORS:
> dt[, c('lon', 'lat') := lapply(.SD, getCoords), .SDcols = c('state', 'county')]
Error in tolower(county) : argument "county" is missing, with no default
In addition: Warning message:
In grep(state, state.abb) :
argument 'pattern' has length > 1 and only the first element will be used
I've seen the following answers but am not able to quite get what I'm doing wrong:
- Loop through data.table and create new columns basis some condition
- R data.table create new columns with standard names
- Add new columns to a data.table containing many variables
- Add multiple columns to R data.table in one function call?
- Assign multiple columns using := in data.table, by group
- Dynamically create new columns in data.table
I am able to achieve what I want by other means (multiple lines, dplyr
or even base R) but I prefer to use the data.table
approach for this.