r - sum in function not working properly -
this question has answer here:
i want create function count values in variable in subsetted dataset, function not working 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 == 4) } count(selected_cyl_6,gear) # [1] 0
the answer should 4. however, if use sum directly correct answer
sum(selected_cyl_6$gear==4) # [1] 4
another example
count(selected_cyl_4,gear) # [1] 0 sum(selected_cyl_4$gear==4) # [1] 8
what doing wrong?
it's using dollar sign shortcut in function. see fortunes::fortune(343)
.
some options, using bracket notation.
first, standard evaluation give variable name in quotes when use function.
count <- function(group, variable) { sum(group[[variable]] == 4) } count(selected_cyl_6, "gear")
if want use non-standard evalution don't need quotes, can use deparse
substitute
in function.
count <- function(group, variable) { sum(group[[deparse(substitute(variable))]] == 4) } count(selected_cyl_6, gear)
Comments
Post a Comment