代码之家  ›  专栏  ›  技术社区  ›  Maxxx

删除R中列中带编号的行

  •  3
  • Maxxx  · 技术社区  · 5 年前

    Country        Population
    123491         9.9
    2348           4.3
    USA            10.1
    Australia      9.1
    

    我想删除国家无效的行,例如123491和2348

    > sapply(df, class)
    
    Country        Population
    factor          numeric
    

    我希望得到以下结果:

    Country       Population
      USA          10.1
      Australia    9.1
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   Jakub.Novotny    5 年前

    library(tidyverse)
    
    Country <- factor(c("123491", "2348", "USA", "Australia"))
    Population <- c(9.9, 4.3, 10.1, 9.1)
    
    df <- data.frame(Country, Population)
    
    df %>%
      filter(!(str_detect(Country, "\\d")))
    
        2
  •  2
  •   Tim Biegeleisen    5 年前

    您可以使用 grepl

    df[!grepl("^\\d+$", df$Country), ]
    
        Country Population
    3       USA       10.1
    4 Australia        9.1
    

    数据:

    df <- data.frame(Country=c("123491", "2348", "USA", "Australia"),
                     Population=c(9.9, 4.3, 10.1, 9.1))
    

    注意:如果你想拒绝一个国家,基于 数字在里面,那就用吧 与模式 \d :

    df[!grepl("\\d", df$Country), ]
    
        3
  •  0
  •   Taher A. Ghaleb    5 年前

    suppressWarnings(df[is.na(as.numeric(as.character(df$Country))),])
    
    #    Country Population
    #3       USA       10.1
    #4 Australia        9.1
    

    所以,如果转换成数字 NA ,表示值为 一种字符类型。我曾经 suppressWarnings

    希望有帮助。