为此,功能效率更高

  • 本文关键字:效率 功能 为此 r
  • 更新时间 :
  • 英文 :


我有一个包含>1亿行的数据框。我需要对带有特定字符(正则表达式(的行进行子集化,但这需要很长时间,因为它逐行读取输入。有没有更有效的方法呢?

数据和函数的示例。谢谢!

search_name = function(name) {
      tf = apply(X = hpot["NAME"], 
                 MARGIN = 1, 
                 FUN = grepl, 
                 pattern = name)
      df = hpot[tf == TRUE, ]
      return(df)
}
hpot = data.frame(NAME = c("alpha", "beta", "gamma", "delta", "alpha2",
                           "beta3", "gamma4", "zeta"),
                  AGE = c(12, 23, 34, 45, 56, 67, 78, 89),
                  HEIGHT = c(123, 134, 145, 156, 167, 178, 189, 190),
                  HOUSE = c("A", "B", "C", "D", "A", "B", "C", "D"),
                  stringsAsFactors = FALSE)
>search_name("beta")
   NAME AGE HEIGHT HOUSE
2  beta  23    134     B
6 beta3  67    178     B

谢谢@lmo!

search_name = function(name) {
      return(hpot[grepl(name, hpot$NAME, fixed = TRUE), ])
}
> search_name("beta")
   NAME AGE HEIGHT HOUSE
2  beta  23    134     B
6 beta3  67    178     B
> search_name("alpha")
    NAME AGE HEIGHT HOUSE
1  alpha  12    123     A
5 alpha2  56    167     A

最新更新