[R] field names as function parameters

tdm philb at philbrierley.com
Sun Oct 11 10:10:35 CEST 2009


Thanks, just the clue I needed, worked a treat.


baptiste auguie-5 wrote:
> 
> Hi,
> 
> I think this is a case where you should use the ?"[[" extraction
> operator rather than "$",
> 
> d = data.frame(a=1:3)
> mytarget = "a"
> d[[mytarget]]
> 
> 
> HTH,
> 
> baptiste
> 
> 2009/10/11 tdm <philb at philbrierley.com>:
>>
>> Hi,
>>
>> I am passing a data frame and field name to a function. I've figured out
>> how
>> I can create the formula based on the passed in field name, but I'm
>> struggling to create a vector based in that field.
>>
>> for example if I hard code with the actual field name
>>
>> Y = df$Target, everything works fine.
>>
>> but if I use the passed in parameter name, it doesn't give me what I
>> want,
>>
>> Y = df$mytarget
>>
>>
>> Here is the function,
>>
>> # trying to pass field name to a function
>> logistictest <- function(df,mytarget)
>> {
>>
>> #library for AUC calculation
>> library(caTools)
>>
>> #build logistic model
>> mytarget <- deparse(substitute(mytarget))
>> myformula <- paste(mytarget," ~ .")
>> myformula <- deparse(substitute(myformula))
>> logistic_reg <- glm(myformula , data=df, family=binomial(link="logit"))
>> print("model build OK")
>>
>> #score up
>> scores <- predict(logistic_reg, type="response", df)
>> print("model scored OK")
>>
>> #calc AUC
>> Y = df$mytarget
>>
>> auc <- colAUC(scores,Y)
>> print("auc calculated OK")
>>
>> }
>>
>> logistictest(df=trainset,mytarget=Target)
>>
>>
>> [1] "model build OK"
>> [1] "model scored OK"
>> Error in as.vector(x, mode) : invalid 'mode' argument
>>
>> --
>> View this message in context:
>> http://www.nabble.com/field-names-as-function-parameters-tp25838606p25838606.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 

-- 
View this message in context: http://www.nabble.com/field-names-as-function-parameters-tp25840951p25841450.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list