2017-09-24 32 views
0

我試圖用不同的字符串替換data.frame中的作者姓名的每個實例,但只有當作者是一個說話者時。舉例來說,如果我們有數據:使用group_by按組替換不同的字符串

test <- data.frame(author = c("jon", "mike", "sam"), text = rep("jon and mike mike and sam sam sam", 3))

我想與其他一些文本時author=="sam"取代「山姆」的每一個實例。

我使用dostr_replace_all做這個嘗試,但還沒有得到它的工作:

test %>% group_by(author) %>% do(mutate(., text2 = str_replace(.$text, eval(parse(text = .$author)), "yay")))

回答

2

str_replace_all矢量化了的字符串,模式和替代。(見?str_replace_all),所以你可以只使用authorpattern

test %>% mutate(new_text = str_replace_all(text, author, 'yay')) 

# author        text       new_text 
#1 jon jon and mike mike and sam sam sam yay and mike mike and sam sam sam 
#2 mike jon and mike mike and sam sam sam jon and yay yay and sam sam sam 
#3 sam jon and mike mike and sam sam sam jon and mike mike and yay yay yay 
+0

出於某種原因,我得到這個錯誤:'錯誤mutate_impl(。數據,點): 評估錯誤:不適用'類型'的方法應用於類「factor」類的對象。 - 任何想法我在做什麼不同/錯誤?我只是複製/粘貼你寫的東西。 – mlinegar

+0

您可能將列作爲因子而不是字符,在構建數據框時嘗試'stringsAsFactors = F'。我用這個'test < - data.frame(author = c(「jon」,「mike」,「sam」),text = rep(「jon and mike mike and sam sam sam」,3),stringsAsFactors = F) ' – Psidom

+0

解決了!謝謝 - 一旦等待期結束,我會盡快接受你的回答。 – mlinegar

相關問題