【问题标题】:How to clean up dataframe column with regular expression?如何用正则表达式清理数据框列?
【发布时间】:2021-04-28 06:48:21
【问题描述】:

考虑这个数据框:

df <- data.frame(Index=c(1:4),
                  Perc1=c("SC(23.43%","12.21%","","(18.44%"))
  Index     Perc1
1     1 SC(23.43%
2     2    12.21%
3     3          
4     4   (18.44%

目标是使用正则表达式清理其列Perc1

想要的结果:

  Index  Perc1
1     1 0.2343
2     2 0.1221
3     3       
4     4 0.1844

我尝试了以下代码,但我得到一个错误和错误的结果。

pattern <- ".*([0-9]+.[0-9]{2})%"
ind <- grep(pattern, df$Perc1, value = FALSE)
df$Perc1 <- sub(pattern, "\\1", df$Perc1)
df$Perc1[-ind] <- NA
df$Perc1 <- as.numeric(df$perc1)/100

【问题讨论】:

    标签: r regex dataframe


    【解决方案1】:

    您可以使用readr::parse_number直接从Perc1获取号码。

    transform(df, Perc1 = readr::parse_number(Perc1)/100)
    
    #. Index  Perc1
    #1     1 0.2343
    #2     2 0.1221
    #3     3     NA
    #4     4 0.1844
    

    【讨论】:

    • 完美,谢谢!我仍然对我的正则表达式模式出了什么问题感到好奇
    • @Andrew 您需要使正则表达式不贪婪。试试这个pattern &lt;- ".*?([0-9]+.[0-9]{2})%"
    【解决方案2】:

    您可以使用regexprregmatches 提取数字。

    r <- regexpr("\\d*\\.?\\d*(?=%)", df$Perc1, perl=TRUE)
    df$Perc1 <- as.numeric(`[<-`(rep(NA, length(r)), r!=-1, regmatches(df$Perc1, r))) / 100
    df
    #  Index  Perc1
    #1     1 0.2343
    #2     2 0.1221
    #3     3     NA
    #4     4 0.1844
    

    你的方法:

    pattern <- ".*?([0-9]+.[0-9]{2})%"   #Adding ? after *
    ind <- grepl(pattern, df$Perc1)      #Change to grepl to get logical vector
    df$Perc1 <- sub(pattern, "\\1", df$Perc1)
    df$Perc1[!ind] <- NA                 #Invert the logical vector
    df$Perc1 <- as.numeric(df$Perc1)/100 #There was a typo perc1 instead of Perc1
    df
    #  Index  Perc1
    #1     1 0.2343
    #2     2 0.1221
    #3     3     NA
    #4     4 0.1844
    

    【讨论】:

      【解决方案3】:

      您可以str_extract 并将数字转换为数字:

      library(stringr)
      df$Perc1 <- as.numeric(str_extract(df$Perc1, "\\d\\d\\.\\d\\d"))/100
      

      结果:

      df
        Index  Perc1
      1     1 0.2343
      2     2 0.1221
      3     3     NA
      4     4 0.1844
      

      【讨论】:

        猜你喜欢
        • 2020-07-03
        • 1970-01-01
        • 2019-08-22
        • 2020-09-10
        • 1970-01-01
        • 2019-04-09
        • 2010-12-31
        • 1970-01-01
        • 2010-10-31
        相关资源
        最近更新 更多