Probably a Dumb Mistake: For Loop warning message even though the output is correct

I am attempting to add the Block FIP based on lat. long points to each row in my data frame, test, using this function I found here: r - Convert Lat/Lon to County Codes using FCC API - Stack Overflow

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!

I'll illustrate with a simple example



(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

Ok I see, thanks. However, the output from the function I call is only one string.

For example,

geo2fips(35.89289, -80.06923)
## output: "370570607001027"

So, in my code I only adding one string to each row. Thus I don't see why I am getting the error

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
}

Ok yes I see, that fixed my issue. Thank you for your help and your timely responses :grinning: !!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.