簡體   English   中英

如何根據自定義 function 返回的值對列進行變異?

[英]How do I mutate column based on value returned from custom function?

我正在嘗試編寫一個 function 可以根據他們的 Spotify ID 在 Spotify 上返回藝術家的流派。 這是與spotifyr package 一起使用的。 考慮以下 dataframe 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    

我的function, 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")

對於每個藝術家 ID,我想在artists dataframe 的每一行上使用它。 我試過這樣做:

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 ,其值由我的 function 針對每個藝術家 ID 返回?

輸出:

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"))

function 未矢量化,請使用rowwise 此外,由於一個id可以返回超過 1 種類型,因此您可以使用toString將所有內容組合在一個逗號分隔的字符串中。

library(dplyr)

artists <- artists %>% rowwise() %>% mutate(genre = toString(get_genre(id)))

我們可以使用map

library(purrr)
library(dplyr)
artists <- artists %>%
              mutate(genre = map_chr(id, ~ toString(get_genre(.x))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM