[R] Using functions/loops for repetitive commands

dereksloan djsloan at liv.ac.uk
Thu May 5 12:16:46 CEST 2011



 I still need to do some repetitive statistical analysis on some outcomes
from a dataset.

Take the following as an example;

id	sex	hiv	age	famsize	bmi	resprate
1	M	Pos	23	2	        16	15
2	F	Neg	24	5	        18	14
3	F	Pos	56	14	        23	24
4	F	Pos	67	3	        33	31
5	M	Neg	34	2	        21	23

I want to know if there are statistically detectable differences in all of
the continuous variables in my data set when subdivided by sex or hiv status
(ie are age, family size, bmi and resprate different in my male and female
patients or in hiv pos/neg patients)
Of course I can use wilcoxon or t-tests e.g:

wilcox.test( age~sex)
wilcox.test(famsize~sex) 
wilcox.test(bmi~sex)
wilcox.test(resprate~sex)
wilcox.test( age~hiv)
wilcox.test(famsize~hiv) 
wilcox.test(bmi~hiv)
wilcox.test(resprate~hiv)

but there must be some easy way of looping/automating this code (i.e. get
all the continuous variables analysed one by one by sex, then analysed one
by one by hiv status).
Obviously my actual dataset is considerably bigger than what is shown here -
I have many variables to assess making the longhand instruction to do every
test pretty unsatisfactory.

I think I can use ‘for’ or some other looping command for this purpose but I
can’t work out how. I think I don’t properly understand how loops work yet
as I'm still quite new to R.

Please could someone help – ideally with an explanation and some quick
sample code? 

Derek


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



More information about the R-help mailing list