0

I'm trying to calculate walk score using walkscoreAPI for multiple Long/Lat pairs. However, the function getWS on takes the first input in the dataframe.

getWS produces a list product, like below.

$status
[1] 1

$walkscore
[1] 0

$description
[1] "Car-Dependent"

$updated
[1] "2017-06-08 22:49:20.313160"

$snappedLong
[1] 38.943

$snappedLat
[1] -77.076

With that in mind I tried to create my own function that would extract $walkscore from the list.

walkscore <- function(x, y){
  walk <- getWS(x, y, "YOUR API KEY")
  walk$walkscore
}

I then attempted to use this in a simple mutate calculation.

library(walkscoreAPI)
library(tidyverse)

# Create sample df
lat <- c(38.942523, 37.942523)
long <- c(-77.076403, -78.076403)
df <- tibble(
  long,
  lat)

#Calculate score
df1 <- df %>% 
  mutate(score = walkscore(long, lat))

This throws the following error

Error: invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdin() else { :
  the condition has length > 1 and only the first element will be used

How can I rewrite this to run getWS for the whole df and pull $walkscore for each row?

Howard Smith
  • 308
  • 2
  • 15

1 Answers1

1

Your problem is that mutate is passing x and y as vectors, not elementwise. You can deal with this by using mapply in your function, like so:

mywalkscore <- function(x, y) {
  walk <- mapply(function(x1,y1) getWS(x1,y1,"YOUR API KEY")$walkscore, x, y)
  unlist(walk)
}

df1 <- df %>% 
  mutate(score = walkscore(long, lat))

I don't have an API key so can't test that this works, but it does get rid of the error you were getting.

Taylor H
  • 436
  • 2
  • 8
  • [This question](https://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega?rq=1) is a good introduction to the *apply family @HowardSmith – Taylor H Jun 09 '17 at 13:47