I make a new row in my data frame called tract and then loop through the data frame with the for loop.
geo2fips <- function(latitude, longitude) {
url <- "https://geo.fcc.gov/api/census/area?lat=%f&lon=%f&format=json"
res <- jsonlite::fromJSON(sprintf(url, latitude, longitude))[["results"]][["block_fips"]]
unique(res)
}
test$tract = rep(NA, nrow(test))
for (i in 1:nrow(test)) {
test$tract[i] = geo2fips(test$Latitude[i], test$Longitude[i])
}
However, this is the warning I get:
Warning messages:
1: In test$tract[i] <- geo2fips(test$Latitude[i], test$Longitude[i]) :
number of items to replace is not a multiple of replacement length
2: In test$tract[i] <- geo2fips(test$Latitude[i], test$Longitude[i]) :
number of items to replace is not a multiple of replacement length
Does anyone see what I am doing wrong? Also, is there an lapply or sapply way to do this that would be faster? My actual data set, not the test version, has 43k rows, so I need to be more efficient. Thanks!
(a_frame <- data.frame(place_for_stuff=NA))
two_things <- c("a","b")
(uniq_two_things <- unique(two_things))
# fine / expected result
a_frame$place_for_stuff[1] <- "x"
a_frame
# putting two things into a place suitable for one thing at a time.
a_frame$place_for_stuff[1] <- uniq_two_things
a_frame
if thats the case, what are you trying to make 'unique' ? you wrote unique(res) after all.
perhaps it returns one result for every case you looked at ; but not every case; theres at least one case where you get multiple results, and the proof is in the error message....
Ok so practically, what can you start by doing; how about making your function let you know of unexpected results
geo2fips <- function(latitude, longitude) {
url <- "https://geo.fcc.gov/api/census/area?lat=%f&lon=%f&format=json"
res <- jsonlite::fromJSON(sprintf(url, latitude, longitude))[["results"]][["block_fips"]]
if (length(res)>1){
print(paste0("More than 1 results for lat: ",latitude, " lon: ",longitude))
}
res
}