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@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.

Reply via email to