首页 > 解决方案 > 在 R 中的冒号之前删除单词时出错

问题描述

我有以下数据框

head(df)

index   song              year  artist  genre   lyrics
    2    Till i am gone    2010    Eminem   Rap   Chorus:It's too much, it's too tough 

我已经完成了其他数据清理,例如使用 gsub 将所有内容转换为小写并删除括号之间的单词,但是,没有找到仅删除单词和它之后的冒号的语法,例如在我的行中,我想删除“合唱:”

在语法之后它应该是

lyrics
It's too much, it's too tough 

以下代码将删除我不想要的冒号之前的所有内容,因为该冒号可以在单元格中的任何位置

gsub(".*:","",foo)

标签: rregex

解决方案


您可以指定仅删除冒号之前的单词。我扩展了您的测试集以显示它有效。

foo = c("Chorus:It's too much, it's too tough ",
    "ABC Chorus:It's too much, it's too tough ")

gsub("\\w+:", "", foo)
[1] "It's too much, it's too tough "  "ABC It's too much, it's too tough "

推荐阅读