I'm working with a dataset of family relationships, with a row for each person and columns describing potential relationships (there is a father column, a mother column, a spouse column, etc.). The columns that I am having problems with are those listing the children of a given individal. I have these as columns titled child1, child2, etc.
I want the end result of the function I'm creating to be a smaller dataset that shows family relationships centered around a particular individual. Since the "child" columns are the ones I am having difficulty with, I'm focusing on the rows that will be included with the relationship column reading "parent."
I have code that allows me to filter to find the parents of any person in the dataset, and when I use it outside of the function, everything works fine. It gives me the parents of any individual whose name I put in place of name
, no matter which of the child columns that individual is in.
dataset %>%
filter_at(vars(matches("^child\\d+$")), any_vars(. == name))
The problem arises when I try to apply this code to my function. I get the following error message: Error in mutate_impl(.data, dots) : Evaluation error: no applicable method for 'tbl_vars' applied to an object of class "quosures".
test_function <- function(name, dataset) {
exact_name <- paste("^", name, "$", sep = "")
family_data <- data.frame(
dataset %>%
mutate(relationship = ifelse(
filter_at(vars(matches("^child\\d+$")), any_vars(. == exact_name)),
"parent",
"other"
)) %>%
filter(relationship != other))
}
I'm guessing that it has something to do with the use of filter_at
within ifelse
. Is there a better way to get the results I want?
(The above is an abbreviated version of my function; I have other ifelse statements in the mutate function that give other relationships, but those don't depend on filter_at and are working fine.)