【问题标题】:How to return ID of student who used ban word in text message (Updated) [duplicate]如何返回在短信中使用禁止词的学生的 ID(更新)[重复]
【发布时间】:2021-11-06 00:19:11
【问题描述】:

我有一个数据框

 ID_Student                    Text_Message
1   John Doe Hell like I want to fxxk around
2 Peter Gynn                 You such an ass
3 Jolie Hope                      Go to hell

我有矢量

> Ban_words
[1] "fxxk" "ass"  "hell"

如何将使用任何禁用词的学生的 ID 与他们使用的词一起返回? 有什么想法吗?

到目前为止我的解决方案。

数据

ID_Student <- c("John Doe", "Peter Gynn", "Jolie Hope", "Mike Tyson")
Text_Message <- c("hell I want to fxxk around", "You such an ass", "Go to hell", "I love you")
Ban_words <- c("fxxk", "ass", "hell")
Student_Message <-data.frame(ID_Student,Text_Message)

数据框应该是这样的

ID_Student               Text_Message
1   John Doe hell I want to fxxk around
2 Peter Gynn            You such an ass
3 Jolie Hope                 Go to hell
4 Mike Tyson                 I love you

代码

for (i in Ban_words){

Detention_List<-Student_Message %>% filter (grepl(i, Text_Message))%>%
        pull(ID_Student)
print(Detention_List)

}

返回

[1] "John Doe"
[1] "Peter Gynn"
[1] "John Doe"   "Jolie Hope"

因此,对于乐队单词“fxxk”,只有约翰使用它。但是对于“地狱”这个词,约翰和朱莉都使用了它。

【问题讨论】:

    标签: r string


    【解决方案1】:

    我们可以使用paste(collapse = "|") 将所有“Ban_worsd”折叠成一个正则表达式,然后使用 grepl 和这个正则表达式来过滤数据框。然后pull 带有名称的向量。如您所见,这返回了除“Mike”之外的所有学生的姓名,因为他没有使用禁止词(请参阅我编辑的数据)。

    library(dplyr)
    
    df %>% filter (grepl(paste(Ban_words, collapse = '|'), Text_Message)) %>%
            pull(student)
    
    [1] "John Doe"   "Peter Gyn"  "Jolie Hope"
    

    数据

    df<-data.frame(student=c('John Doe', 'Peter Gyn', 'Jolie Hope', 'Mike'), Text_Message=c('I want to fxxk around', 'You such an ass', 'Go to hell', "I love you"))
    
    > df
         student          Text_Message
    1   John Doe I want to fxxk around
    2  Peter Gyn       You such an ass
    3 Jolie Hope            Go to hell
    4       Mike            I love you
    
    Ban_words<-c("fxxk", "ass",  "hell")
    

    【讨论】:

    • 谢谢!我想你必须以某种方式使用grepl。根据我的研究要求慢慢学习R。 ID实际上是蛋白质ID,短信实际上是蛋白质序列,而禁止词实际上是我想在蛋白质序列中检测的短序列表。
    • 另外,您可以学习如何使用 stringr 包来操作字符串。我认为它比基本 R 更直观。在这种情况下,我们可以使用 str_detect() 而不是 grepl() stringr.tidyverse.org
    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多