编写一个带引号的字符串参数的函数

时间:2017-03-27 10:56:18

标签: r

我希望能够使用类似的内容调用下面的函数

conditional_prob_bool(Class=='democrat',V1=='y',df) 

并且

consequent_bool=df$Class=='democrat'

antecedent_bool=df$V1=='y'

在函数体内。

但它似乎没有按照我想要的方式工作,可能是因为引号。有人可以建议我如何更改代码以便我可以获得这些作业吗?

install.packages("mlbench")
install.packages("mice")
library(mlbench)
library(mice)
data("HouseVotes84")
imputeddf=mice(HouseVotes84,m=1,maxit=50,meth='pmm',seed=500)
completedData <- complete(imputeddf,1)
df=completedData
df$names<-rownames(df)
conditional_prob_bool=function(spec1,spec2,df){ 

  consequent_bool=df$spec1 
  consequent_event=df[consequent_bool,] 

  antecedent_bool=df$spec2 
  antecedent_event=df[antecedent_bool,] 

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df)) 
} 

#Currently when I run it I get
> conditional_prob_bool(Class=='democrat',V1=='y',df)
[1] NaN
#however manually running the body like this, I get what I want.
> consequent_bool=df$Class=='democrat'
> consequent_event=df[consequent_bool,]
> antecedent_bool=df$V1=='y'
> antecedent_event=df[antecedent_bool,]
> prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df)
[1] 0.8376963

谢谢。

1 个答案:

答案 0 :(得分:0)

这是功能:

conditional_prob_bool <- function(spec11, spec12, spec21, spec22, df){ 

  consequent_bool <- df[,spec11] == spec12
  consequent_event <- df[consequent_bool,] 

  antecedent_bool <- df[,spec21] == spec22
  antecedent_event=df[antecedent_bool,]

  return(prob(intersect_event(consequent_event,antecedent_event,df),df)/prob(antecedent_event,df))
}

结果:

> conditional_prob_bool('Class', 'democrat', 'V1', 'y', df)
[1] 0.8376963

正如我告诉你的,如果你的功能不起作用,请逐行调试它以查看错误的来源。