【问题标题】:Find sub-string / replace full-string with new value across entire data.frame in R在R中的整个data.frame中查找子字符串/用新值替换完整字符串
【发布时间】:2015-12-08 12:51:23
【问题描述】:

我有一个包含许多列的大型数据框。对于这些列的子集,我想匹配一个子字符串并替换

两列子集的示例如下所示:

df <- data.frame(list(A=c("0/0:52,0:52:High_Confidence:99:0","0/0:2,0:2:Low_Confidence:3:0,3,45,1858","0/0:52,0:52:High_Confidence:99:0,135,1858","0/0:9,0:9:Low_coverage_High_quality:21:0,21,291"), B=c("0/0:5,0:5:Low_Confidence:15:0,15,194","0/0:21,0:21:High_Confidence:51:0,51,675","0/0:1,0:1:Low_Confidence:3:0,3,39","0/0:17,0:17:High_Confidence:48:0,48,609")))

我想使用 grepl 类型命令将其中带有“Low_Confidence”的字段替换为 ./。跨越整个数据框。

我试过了:

df[grepl(".*Low_Confidence.*", df)] <- "./." # replaces ALL values with ./.
df[agrep(".*Low_Confidence.*", df)] <- "./." # Does nothing

df[grep(".*Low_Confidence.*", df)] <- "./." 
df[grep("Low_Confidence", df)] <- "./."

其中大多数返回 data.frames,相关列中的所有值都带有 ./。无论它们是否符合 Low_Confidence 标准。

我也尝试将 data.frame 转换为矩阵

df  <- as.matrix(df)
df[df==".*Low_Confidence.*"]  <- "./." # does nothing

没有成功。我知道如果我一次只写一列是可能的,例如:

df$V85[grepl(".*Low_Confidence.*", df$V85)] <- "./."

但是对于高度重复的 100 列。

因此,我正在寻找一种解决方案,该解决方案将查找/替换通配符,以匹配 data.frame 中所有或列子集的整个字符串(不仅仅是匹配的文本)或列的子集(两者都可以)。

谢谢!

【问题讨论】:

    标签: regex r dataframe grepl


    【解决方案1】:

    首先,将列转换为字符(此步骤是必需的,因为您提供的数据框包含因子。以这种方式替换因子的值会导致 NA),然后将 Low_Confidence 单元格替换为“./”。使用应用:

    df1 <- apply(df,2,as.character)
    df1[apply(df1,2,function(x) grepl("Low_Confidence",x))] <- "./."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多