[R] Using functions/loops for repetitive commands

dereksloan djsloan at liv.ac.uk
Thu May 5 16:01:24 CEST 2011


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))
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 




--
View this message in context: http://r.789695.n4.nabble.com/Using-functions-loops-for-repetitive-commands-tp3498006p3498427.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list