Laura
Laura

Reputation: 519

Error in grouping variable trying to create a function to get frequency counts using dplyr in R

I have a dataset which looks like this

df1 <- data.frame (
age = rep(c("40-44", "45-49", "50-54", "55-59", "60-64"),4),
dep = rep(c("Dep1", "Dep2", "Dep3", "Dep4", "Dep5"),4),
ethnic_1 = c(rep("M",4),rep("NM",7),rep("P", 3), rep("A", 6)),
ethnic_2 = c(rep("M",8),rep("NM",6),rep("P",2),rep("A", 4)),
gender = c(rep("M",10), rep("F",10))
)

What I want to do, is get a comparison of the two ethnicity classifications in these dataframes, by creating and running the following function

Comp_fun <- function(data, var1, ...) {

group_var <- quos(...)

var_quo <- enquo(var1)

df <- data %>% 
 group_by(!!! group_var) %>%
 summarise (n = n()) %>%
 spread(key = !!! var_quo, value = count)

return(df)
}

eth_comp <- Comp_fun(df1, ethnic_1, ethnic_1, ethnic_2)

When I run this code, I get the following error message Error: Invalid column specification

What I want as output from this is a 4 x 4 table, showing the count of ethnic 1 along the horizontal, and the count of ethnic 2 along the vertical, and showing the numbers where they match, and where they don't.

I think I'm using the quo enquo incorrectly. Can anyone tell me where I'm going wrong?

Upvotes: 1

Views: 33

Answers (1)

akrun
akrun

Reputation: 887153

There is no 'count' variable. It should be 'n'. Also, 'var_quo' is a quosure and not quosures. So, it can be evaluated with !!

Comp_fun <- function(data, var1, ...) {

  group_var <- quos(...)

  var_quo <- enquo(var1)

  data %>% 
    group_by(!!! group_var) %>%
    summarise (n = n()) %>%
    spread(key = !! var_quo, value = n)


}

eth_comp <- Comp_fun(df1, ethnic_1, ethnic_1, ethnic_2)
eth_comp
# A tibble: 4 x 5
#  ethnic_2     A     M    NM     P
#  <fct>    <int> <int> <int> <int>
#1 A            4    NA    NA    NA
#2 M           NA     4     4    NA
#3 NM          NA    NA     3     3
#4 P            2    NA    NA    NA

Upvotes: 2

Related Questions