【问题标题】:r - Replace text in data frame columnr - 替换数据框列中的文本
【发布时间】:2018-03-21 15:27:06
【问题描述】:

如果答案很简单,我深表歉意;我是 R 新手,但找不到解决方案

我有一个数据框,我感兴趣的列(“主题”)的每一行都有一个单词列表。

title  subject
-----  -----------------------------------------------
 A     c("health sciences", "life sciences")
 B     c("biochemistry", "medicine", "life sciences")
 C     c("physics and astronomy", "mathematics")

我想用“生物学”替换(并因此分类)每个标题的所有与生物学相关的词。所以基本上,如果任何标题都有与生物学相关的科目列表,那么他们的科目将被更简单的“生物学”所取代。

所以我的数据框看起来像这样:

title  subject
-----  -----------------------------------------------
 A     biology
 B     biology
 C     c("physics and astronomy", "mathematics")

如何将所有以关键前缀(例如“bio”、“health”、“med”、life”等)开头的单词替换为“biology”?

【问题讨论】:

  • 你可以做例如:df$subject <- gsub("bio", "biology", df$subject)
  • 对于“健康”、“医学”等,您必须这样做。这对你的df有用吗?一条建议:为您的问题提供一个可重复的示例。然后我们可以在发布答案之前自己快速测试一下:)
  • 我问了一个有点类似的问题,它需要data.table stackoverflow.com/questions/48629202/…

标签: r regex dataframe replace gsub


【解决方案1】:

尝试适配代码:

一个玩具数据框架

df<-data.frame(title=c("A","B"),subject=c("health sciences", "other stuffs"))

解决办法:

toMatch<-c("^bio","^health", "^med", "^life")
df$subject<-as.character(df$subject)
df[grepl(paste(toMatch,collapse="|"),df$subject ),"subject"]<-"biology"

你的输出:

df
  title      subject
1     A      biology
2     B other stuffs

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2014-02-06
    • 2012-07-16
    • 2016-02-08
    • 1970-01-01
    • 2012-08-02
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多