更高效的功能呢?

时间:2017-04-10 15:44:19

标签: 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

1 个答案:

答案 0 :(得分:0)

谢谢@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