So I know this is probably a stupidly easy question, but how would I use map if I wanted to use it on a function that took 2 arguments:
- The data frame I want to use
- The row number of the data frame
However, I do not change the data frame within the function, so if I have a data frame called mydata
I want each map
function to go through whatever rows of mydata
I choose, but then be able to generalize the map
function for whatever data frame I want.
Here's an example of what I currently have -- which works. Within the function, I explicitly call a specific data frame, mydata
library(spotifyr)
library(tidyverse)
library(stringdist)
Sys.setenv(SPOTIFY_CLIENT_ID = "xxx") # from Spotify' API page
Sys.setenv(SPOTIFY_CLIENT_SECRET = "xxx") # from Spotify's API page
access_token <- get_spotify_access_token()
Artist <- c("Spiritualized", "Fleet Foxes", "Ween")
Album <- c("Sweet Heart, Sweet Light", "Helplessness Blues", "Quebec")
mydata <- data_frame(Artist, Album)
mydata
#> # A tibble: 3 x 2
#> Artist Album
#> <chr> <chr>
#> 1 Spiritualized Sweet Heart, Sweet Light
#> 2 Fleet Foxes Helplessness Blues
#> 3 Ween Quebec
closest_match <- function(string, string_vector){
string_vector[amatch(tolower(string),
tolower(string_vector),
maxDist = 6,
method = "lv",
weight = c(d = 1, i = 0.1, s = 1))]
}
# sets up progress bar
pb_1 <- mydata%>%
tally() %>%
progress_estimated(min_time = 0)
get_album_data <- function(row_num) {
pb_1$tick()$print()
seq(3, 5, by = 0.001) %>%
sample(1) %>%
Sys.sleep()
get_artist_audio_features(mydata$Artist[row_num], return_closest_artist = TRUE) %>%
filter(album_name == closest_match(mydata$Album[row_num], album_name)) %>%
mutate(score = mydata$Score[row_num], df_artist_name = mydata$Artist[row_num], df_album_name = mydata$Album[row_num])
}
map_df(1:2, get_album_data)
Here's an example of what I want to do, but what doesn't work. Here I have an argument for data so I can use the function on different data frames.
get_album_data <- function(row_num, data) {
pb_1$tick()$print()
seq(3, 5, by = 0.001) %>%
sample(1) %>%
Sys.sleep()
get_artist_audio_features(data$Artist[row_num], return_closest_artist = TRUE) %>%
filter(album_name == closest_match(data$Album[row_num], album_name)) %>%
mutate(score = data$Score[row_num], df_artist_name = data$Artist[row_num], df_album_name = data$Album[row_num])
}
map2_df(1:2, mydata, get_album_data)
Created on 2018-04-12 by the reprex package (v0.2.0).
With an error message:
Error:
.x(2) and
.y(4) are different lengths
Thanks for any help.