From a0fbd037681863ca997a9d21bab1c15269428a0b Mon Sep 17 00:00:00 2001 From: Holger Brandl Date: Mon, 14 Nov 2016 11:47:55 +0100 Subject: [PATCH] added dataframe search functions. --- R/core_commons.R | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/R/core_commons.R b/R/core_commons.R index 3b44780..033e064 100644 --- a/R/core_commons.R +++ b/R/core_commons.R @@ -262,8 +262,27 @@ replaceNA <- function(x, withValue) { x[is.na(x)] <- withValue; x } + +## see http://stackoverflow.com/questions/17288222/r-find-value-in-multiple-data-frame-columns/40586572#40586572 +## case-insenstive search all columns of a data-frame with a fixed search term +search_df = function(df, search_term){ + apply(df, 1, function(r){ + any(str_detect(as.character(r), fixed(search_term, ignore_case=T))) + }) %>% subset(df, .) +} + + +## filter a data-frame for those rows where at least one column is matching the given expression (that must evaluate to a boolean vector for each row). +match_df = function(df, search_expr){ + filter_fun = eval(substitute(function(x){search_expr})) + + apply(df, 1, function(r) any(filter_fun(r))) %>% subset(df, .) +} + + ## todo still needed since there's if_else in dplyr now safe_ifelse <- function(cond, yes, no) { + warning("DEPRECATED Use dplyr::if_else instead") #browser() isfacOrChar <- function(x) class(x) %in% c("factor", "character") -- GitLab