[R] help needed on function call
Erik Iverson
iverson at biostat.wisc.edu
Tue Mar 4 19:15:36 CET 2008
It isn't clear to me what output you would like to have by your
description.
However, there certainly is a clearer way of getting there than your
functions. If you better define what output you'd like to have (i.e.,
what your table should look like), I may be able to offer some suggestions.
You may want to look at ?prop.table to see if it helps you though.
Best,
Erik Iverson
rmail ye wrote:
> Hi there,
>
> I am confused about fucntion call. After defining a function, I called it
> within another function.
>
> dt<-cars; #a copy of R internal dataset "cars" created;
> dt$cat1<-ifelse(dt$speed<20,0,1);
> dt$ind<-ifelse(dt$speed<15,1,2); #group variable;
>
> freqtot <- function(data,var){
> attach(data,warn.conflicts=FALSE)
> x1 <- data.frame(table(var))
> names(x1) <- c("Group","cnt")
> x1$pct<-round(x1$cnt/nrow(data)*100,1)
> return(x1)
> }
>
> freqgrp <- function(dt,var,grp,grpcnt){
> xx<-freqtot(dt,var)
> for(i in 1:grpcnt) {
> assign(paste("x",i,sep=""),subset(dt,grp==i))
> df<-eval(parse(text=paste("x",i,sep="")))
> yy <- freqtot(df,cat1);
>
> names(yy)<-c("Group",paste("grp_",i,"_cnt",sep=""),paste("grp_",i,"_pct",sep=""))
> xx<-merge(xx,yy,by.x="Group",all=TRUE)
> }
> print(xx)
> }
>
> The output is
>> xyz <- freqgrp(dt,cat1,ind,2)
> Group cnt pct grp_1_cnt grp_1_pct grp_2_cnt grp_2_pct
> 1 0 38 76 23 100 15 55.6
> 2 1 12 24 NA NA 12 44.4
> But if I substitue the variable "cat1" in line {yy <- freqtot(df,cat1)}, it
> doesn't output the correct results.
>
> The motivation to write the 2 functions is putting the count and percentage
> for overall & each individual group together, and write the data frame into
> a .csv file.
>
> Thanks,
> Sean
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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