I have a dataframe and I am trying to manipulate the results with dplyr for practice. My standard approach works, however whenever I try to run it wrapped in a function, I get Error: Result must have length 1, not 12.
I should be getting two print outs. Here is a reproducible example:
library(tidyverse)
library(dplyr)
dat <- data.frame(Class= c("3rd","First","2nd","3rd","First","2nd","3rd","First","2nd","3rd","First","2nd"),
Sex= c("Male","Male","Male","Female","Female","Female","Male","Male","Male","Female","Female","Female"),
Age= c("Child","Child","Child","Child","Child","Child","Adult","Adult","Adult","Adult","Adult","Adult"),
Survived= c("No","No","Yes","No","Yes","No","Yes","Yes","No","Yes","No","Yes"))
multiple_col_selection2 <- function(data, sex_var, age_var){
data %>%
group_by(data[,4],data[,2],data[,3])%>%
filter(.[[2]]== sex_var & .[[3]]== age_var) %>%
count() %>%
ungroup()%>%
add_row({{Sex}} = "Total", n= sum(.$n)) -> dataset
paste0(round(dataset$n[1] * 100/dataset$n[3], 2), "% NOT survived.")
paste0(round(dataset$n[2] * 100/dataset$n[3], 2), "% survived.")
}
multiple_col_selection2(dat,"Female","Adult") #Error: Result must have length 1, not 12
#Whereas if I do it standalone, it works
ex_dat <- dat %>%
group_by(Sex, Age, Survived)%>%
filter(Sex== "Female" & Age== "Adult") %>%
count()%>%
ungroup()%>%
add_row(Sex = "Total", n= sum(.$n))
paste0(round(ex_dat$n[1] * 100/ex_dat$n[3], 2), "% NOT survived.")
#[1] "33.33% NOT survived."
paste0(round(ex_dat$n[2] * 100/ex_dat$n[3], 2), "% survived.")
#[1] "66.67% survived."
I have read these posts here: Wrapping dplyr filter in function results in "Error: Result must have length 4803, not 3"
Creating a function with an argument passed to dplyr::filter what is the best way to work around nse?
However my approach is different than the approaches in these links. This is my first time using dplyr.