Using a Variable Where Quotes Are Needed in Function Argument


#1

I’m trying to loop through a function – get_artists() – where the first argument is required to be string within quotations. The argument is supposed to be an artist’s name, such as "Radiohead". However, since I’m looping, I need to set it to be my variable name, as below.

get_album_data <- function(x) {
  get_artists(mydata$Artist[x], return_closest_artist = TRUE) %>%
    get_albums(mydata$Album[x]) %>%
    get_album_tracks()
}

This won’t work though, since mydata$Artist[x] isn’t in quotes. And if I do:

get_album_data <- function(x) {
  get_artists("mydata$Artist[x]", return_closest_artist = TRUE) %>%
    get_albums(mydata$Album[x]) %>%
    get_album_tracks()
}

It’ll act as if mydata$Artist[x] is the name of the artist.

Any ideas? I’m not really sure how to phrase this, so apologies if my question is incoherent.


#2

I’m not sure what you are trying to achieve, but couple of pointers.

As is tradition, first you should try to get your problem into reprex. This will help everyone, including yourself.

Second, what should be the result of the code mydata$Artist[x]? String? I imagine mydata is a dataframe and Artist is a column in a dataframe, so using mydata$Artist (btw, it is better to not use $ as it has multiple corner-cases that are likely to bite you down the road, instead you can use mydata[["Artist"]], for example) will return a vector that you can subset using integers, not strings. So x in your function signature can’t be a string.

Finally, I’m fairly certain that you are trying to do is called quasiquotation or tidy evaluation, so you can use these name to search this forum or Google, if you like. There is a great webinar by Lionel Henry on this concept.


#3

Like @mishabalyasin mentioned, @eoppe1022, this is a perfect use case for tidy eval.

I find @Edwin’s post on this (see link below) to be incredibly helpful.

I’ve also rounded up some other posts/examples of tidy evaluation here: