[R] Odp: Using Function

Petr PIKAL petr.pikal at precheza.cz
Tue Aug 2 15:04:36 CEST 2011


Hi

> 
> Hi,
> 
> I have some simple statistics to calculate for a large 
> number of variables.
> I created a simple function to apply to variables.
> I would like the variable name to be placed automatically.
> I tried the following function but is not working.
> 
> desc = function(x){
>                  media = mean(x, na.rm=T)
>                  desvio = sd(x, na.rm=T)
>                  cv = desvio/media*100
>                  saida = cbind(media, desvio, cv)
>                  colnames(saida) = c(NULL, 'Média', 
> 'Desvio', 'CV')
>                  rownames(saida) = c(x)
>                  saida
>  }

You are quite close. This seems to do what you want if I presume that your 
variables are located in data frame

desc = function(x){
                 media = mean(x, na.rm=T)
                 desvio = sd(x, na.rm=T)
                 cv = desvio/media*100
                 saida = data.frame(Media=media, Desvio=desvio, CV=cv)
                 saida
 }

iris4 <- iris[,1:4]

sapply(iris4, desc)
       Sepal.Length Sepal.Width Petal.Length Petal.Width
Media  5.843333     3.057333    3.758        1.199333 
Desvio 0.8280661    0.4358663   1.765298     0.7622377 
CV     14.17113     14.25642    46.97441     63.55511 

If you want switch rows and cols use 

t(sapply(iris4, desc))

Regards
Petr


> 
> desc(Idade)
> 
>          Média  Desvio      CV
> Idade 44.04961 16.9388 38.4539
> 
> How do you get the variable name is placed as the first 
> element?
> 
> My objective is get something like:
> 
> rbind(
> desc(Altura),
> desc(Idade),
> desc(IMC),
> desc(FC),
> desc(CIRCABD),
> desc(GLICOSE),
> desc(UREIA),
> desc(CREATINA),
> desc(CTOTAL),
> desc(CHDL),
> desc(CLDL),
> desc(CVLDL),
> desc(TRIG),
> desc(URICO),
> desc(SAQRS),
> desc(SOKOLOW_LYON),
> desc(CORNELL),
> desc(QRS_dur),
> desc(Interv_QT)
> )
> 
> Thanks a lot,
> 
> --------------------------------------
> Silvano Cesar da Costa
> Departamento de Estatística
> Universidade Estadual de Londrina
> Fone: 3371-4346
> 
> ______________________________________________
> 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