【发布时间】:2021-04-04 09:28:07
【问题描述】:
我正在尝试编写一个函数,该函数可以根据他们的 Spotify ID 在 Spotify 上返回艺术家的流派。这是spotifyr 包。考虑以下数据框artists:
# A tibble: 6 x 2
id name
<chr> <chr>
1 6ltzsmQQbmdoHHbLZ4ZN25 Lord Huron
2 35U9lQaRWSQISxQAB94Meo America
3 22WZ7M8sxp5THdruNY3gXt The Doors
4 2MSlGNpwXDScUdspOK6TS7 Home Free
5 4GITZM5LCR2KcdlgEOrNLD The Foundations
6 2jgPkn6LuUazBoBk6vvjh5 The Zombies
我的函数get_genre定义如下:
get_genre <- function(x) {
artist <- get_artist(x)
artist <- enframe(artist)
genre <- artist[3,2]
genre <- as.data.frame(genre)
return(genre)
}
例如,对于 id 6ltzsmQQbmdoHHbLZ4ZN25 ,它返回:
c("indie folk", "indie pop", "stomp and holler")
我想在 artists 数据框的每一行上使用它,用于每个艺术家 ID。我试过这样做:
artists <- artists %>% mutate(genre = get_genre(id))
但这会产生以下错误:
Error: Problem with `mutate()` input `genre`. x length(url) == 1 is not TRUE i Input `genre` is `get_genre(id)`.
如何改变一个新列 genre,其值由我的函数为每个艺术家 ID 返回?
DPUT:
structure(list(id = c("6ltzsmQQbmdoHHbLZ4ZN25", "35U9lQaRWSQISxQAB94Meo",
"22WZ7M8sxp5THdruNY3gXt", "2MSlGNpwXDScUdspOK6TS7", "4GITZM5LCR2KcdlgEOrNLD",
"2jgPkn6LuUazBoBk6vvjh5"), name = c("Lord Huron", "America",
"The Doors", "Home Free", "The Foundations", "The Zombies")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
【问题讨论】: