[R] Using functions/loops for repetitive commands

David Winsemius dwinsemius at comcast.net
Thu May 5 17:04:21 CEST 2011


On May 5, 2011, at 10:01 AM, dereksloan wrote:

> Your code may be untested but it works - also helping me slowly to  
> start
> understanding how to write functions. Thank you.
>
> However I still have difficulty. I also have some categorical  
> variables to
> analyse by age & hiv status - i.e. my dataset expands to (for  
> example);
>
> id	sex	hiv	age	famsize	bmi	resprate   smoker   alcohol
> 1	M	Pos	23	2	       16	15             Y           Y
> 2	F	Neg	24	5	       18	14             Y           Y
> 3	F	Pos	56	14	       23	24             Y           N
> 4	F	Pos	67	3	       33	31             N           N
> 5	M	Neg	34	2	       21	23             N           N
>
>
> Using the template for the code you sent me I thought I could  
> analyse the
> categorical variables by sex & hiv status using a chiq-squared test;
>
> Long-hand this would be;
>
> chisq.test(smoker,sex)
> chisq.test(alcohol,sex)
> chisq.test(smoker,hiv)
> chisq.test(alcohol,hiv)
>
> Again I wanted to use a function to loop automate it and thought I  
> could
> write;
>
> categ<-c(smoker,alcohol)
> group.name<-c(sex,hiv)
> bl.chisq<-function(categ,group.name,<dataframe name>){
> lapply(categ,
> function(y){
> form2<-as.formula(paste(y,group.name))

I haven't tested it but I suspect you failed to note that Eichner used  
sep="~" in his paste argument to as.formula().

> chisq.test(form2,<dataframe name>)
> })
> }
>
> bl.chisq(categ,group.name,<data frame name>)
>
> but I get an error message:
>
> Error in parse(text = x) : unexpected symbol in "smoker sex"
>
> What is wrong with the code? Is is because the wilcox.test is a  
> formula
> (with a ~ symbol for modelling) whilst the chisq.test simply  
> requires me to
> list raw data? If so how can I change my code to automate the  
> chisq.test in
> the same way I did for the wilcox.test?
>
> Many thanks for any help!
>
> Derek
>
>


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list