fank fank - 2 months ago 21
R Question

sum in function not working properly

i want to create a function to count the values in a certain variable in a subsetted dataset but my function not working as it supposed to.

selected_cyl_6 <- subset(mtcars, mtcars$cyl==6)
selected_cyl_4 <- subset(mtcars, mtcars$cyl==4)

count <- function(group,variable) {
sum(group$variable == 1)
}

count(selected_cyl_6,gear)


however if I use the sum directly i get the correct answer

sum(selected_cyl_6$gear==4)


another example

count(selected_cyl_4,gear)
sum(selected_cyl_4$gear==4)


what am I doing wrong? thank you so much for any advice

Answer

It's from using the dollar sign shortcut in your function. See fortunes::fortune(343).

Some options, using bracket notation.

First, with standard evaluation you would give your variable name in quotes when you use the function.

count <- function(group, variable) {
    sum(group[[variable]] == 4)
}

count(selected_cyl_6, "gear")

If you want to use non-standard evalution so you don't need to quotes, you can use deparse with substitute in your function.

count <- function(group, variable) {
    sum(group[[deparse(substitute(variable))]] == 4)
}

count(selected_cyl_6, gear)