【问题标题】:remove a string starting with @ in data frame column in R在R中的数据框列中删除以@开头的字符串
【发布时间】:2015-10-27 19:46:19
【问题描述】:

假设数据框是df,列foo。有没有办法删除R中数据框列中以@开头的字符串。

例子:

df <- data.frame(foo=c("@john is awesome than @steve", 
                                        "@steve is good","@mike is nice"))

df
                           foo
1 @john is awesome than @steve
2               @steve is good
3                @mike is nice

如何删除以@开头的整个名称@john、@Steve、@mike。

最终输出应该是

               foo
1  is awesome than 
2          is good
3          is nice

我想删除数据框df 中以分隔符@ 开头的列foo 中的所有字符串。

【问题讨论】:

  • gsub("@.*?[ ]| @.*?$","",df$foo) [1] "is awesome than" "is good" "is nice"
  • within.list(df, {foo &lt;- gsub("[ ]*\\@[^ ]+", "", foo)})

标签: r string


【解决方案1】:

我和 Richard Scriven 的 cmets 的组合。

df$foo <- gsub(" ?@\\w+ ?", "", df$foo)
df
#               foo
# 1 is awesome than
# 2         is good
# 3         is nice

@\\w+ 与后跟一个或多个字母的符号匹配。 ? 匹配开头和结尾的可选空格。

所以总之它会寻找匹配的

[optional single space]@[one word][optional single space]

【讨论】:

    【解决方案2】:

    您可能想查看包stringr 并使用str_replace_all 匹配以@ 开头的正则表达式以及以下任何单词:

    library("stringr")
    
    str_replace_all(df$foo, " ?@\\w+ ?", "")
    
    [1] "is awesome than steve" 
    [2] "is good"             
    [3] "is nice"
    

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 2021-09-25
      • 2015-07-04
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多