2016-09-12 182 views
0

我想創建一個函數來計算子集數據集中某個變量的值,但是我的函數並沒有像預期的那樣工作。求和功能無法正常工作

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 

答案應該是4。但是,如果我直接用總和我得到正確的答案

sum(selected_cyl_6$gear==4) 
# [1] 4 

又如

count(selected_cyl_4,gear) 
# [1] 0 
sum(selected_cyl_4$gear==4) 
# [1] 8 

我在做什麼錯?

回答

2

它是從你的函數中使用美元符號的快捷方式。請參閱fortunes::fortune(343)

一些選項,使用括號表示法。

首先,使用標準評估時,您將在使用該函數時將變量名用引號引起來。

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

count(selected_cyl_6, "gear") 

如果你想使用非標準的評價;所以你不需要報價,您可以使用deparse在你的函數substitute

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

count(selected_cyl_6, gear)