How do i modify the dplyr function to not get Error: Column `column` is unknown?

Viewed 157

Hi I am keep getting the error Error: Column column is unknown from dplyr. I can't modify the function to get rid of the error. The reason why I want to make this function because I have to repeat the process for other variables.
data can be found here: http://www.personal.psu.edu/dlp/w540/datasets/titanicsurvival.csv

one_col_count <- function(data, column){

  data %>%
        group_by(column)%>%
        count() %>%
        ungroup() %>%
        add_row(column= "Total",  n= sum(.$n)) -> dataset

  return(dataset)
}

survival_count <- one_col_count(dat, as.name("Survived"))

#dat is a data.frame where I changed to types of every column to factor

#Whereas this works
#survival_count <- dat %>%
#                     group_by(Survived)%>%
#                     count() %>%
#                     ungroup() %>%
#                     add_row(Survived= "Total", 
#                             n= sum(.$n))

#And I get the output
## A tibble: 3 x 2
#  Survived     n
#  <fct>    <int>
#1 No        1490
#2 Yes        711
#3 Total     2201

I've looked several stack overflow with this error, but they had different issues and didn't relate to mine. Please note that my R vocabulary is not that great, so maybe there is an answer, but having lack of proper vocab, I may have overlooked it. Any help or hint or direction to get rid of the error? Really appreciate it.

1 Answers

Use {{}} to pass column names as unquoted.

library(dplyr)

one_col_count <- function(data, column){

  data %>%
    group_by({{column}})%>%
    count() %>%
    ungroup() %>%
    add_row({{column}} := "Total",  n= sum(.$n))

   return(dataset)
}

one_col_count(dat, Survived)
Related