[R] How to modify function for list

Christos Hatzis christos at nuverabio.com
Wed Oct 3 07:02:59 CEST 2007


Instead of 

> bmisds(age,gender,bmi)

Try the vectorized version 

> mapply(bmisds, age, gender, bmi)

See ?mapply

-Christos

 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Chung-hong Chan
> Sent: Wednesday, October 03, 2007 12:31 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] How to modify function for list
> 
> Dear R Gurus,
> 
> I have a function which calculate the BMI standard deviation 
> score based on the age and gender specific L, M, S value.
> I have written a function like this
> 
> bmisds <- function (age, gender, bmi){
>   if (age ==1 & gender ==1)
>     {
>       bmif <- c(-1.013,16.133,0.07656)
>     }
>   else if (age ==1 & gender ==0)
>     {
>       bmif <- c(-1.79,16.421,0.07149)
>     }
>   else if (age == 2 & gender == 1)
>     {
>       bmif <- c(-1.403,15.58,0.07342)
>     }
>   else if (age == 2 & gender == 0)
>     {
>       bmif <- c(-2.045,15.861,0.07116)
>     }
> ....
> 
>       (((bmi/bmif[2])**bmif[1] -1)/(bmif[1]*bmif[3])) }
> 
> This function work when I supply a single variable, e.g. 
> bmisds(1,0,16)
> 
> When I try it with a list, e.g.
> age <- c(12,13,14)
> gender <- c(0,1,1)
> bmi <- c(14,15,16)
> bmisds(age,gender,bmi)
> 
> This function give me wrong answer and error msg.
> Warning messages:
> 1: the condition has length > 1 and only the first element 
> will be used in: if (age == 1 & gender == 1) {
> 
> 
> How can I midify this function to work with list/vector?
> 
> regards,
> C
> 
> 
> --
> CH Chan
> Research Assistant - KWH
> http://www.macgrass.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.
> 
>



More information about the R-help mailing list