[R] Zero counts lost with table() in functions

Erik Iverson eriki at ccbr.umn.edu
Mon Jun 14 22:36:46 CEST 2010



Ottar Kvindesland wrote:
> Hi,
> 
> I am collecting replies from a survey and counts replies by the table()
> function. The function below carries two
> data frames and counts the observations of the findings in the first
> parameter vector given the value of the second as shown in the code below.
> 
> My trouble is that the vector kp_vec at the end of the inner loop seems to
> ignore the value when the
> table() counts zero occurences of one of the outcomes. I will have
> 
>     y     n
>     34   0
> 
> This is not picked up in the matrix row after the loops with something like
> 
>                                      "y"   "n"     "y"
> "Funding"   "Survival"      12     5       34
> 
> where the last "n" value is missing. This causes my returned data frame to
> fail and in all, rather miserable for the plot.
> 
> I see the point of this in a way, so I believe it is not a bug. I'd love to
> get my zero back. Is it a subtle point in R I have missed?
> 
> 
> kpi_test <- function ( paramvec, kpivec ) {
> kp_vec <- c()
> res_kpi_y <- c()
> res_kpi_n <- c()
> 
> tmp_param <- c()
> tmp_kpi <- c()
> 
> for(param_no in seq(from=1, to=length(paramvec), by = 1)) {
> tmp_param <- paramvec[param_no]
> for (kpi_no in seq(from=1, to=length(kpivec), by = 1)) {
> tmp_kpi <- kpivec[kpi_no]
> res_kpi_y <- table( tmp_param [ tmp_kpi == 'y' ] )
> res_kpi_n <- table( tmp_param [ tmp_kpi == 'n' ] )
> kp_vec <- c(kp_vec, names(tmp_param), names(tmp_kpi), res_kpi_y, res_kpi_n )
> }
> }
> matrix_vector <- matrix(kp_vec, ncol=6, byrow=T)
> fres <- data.frame(matrix_vector)
> return( fres )
> }

Is it possible to provide test data that shows how your function is not 
behaving as you'd like?  It's probable that your function can be reduced 
to a line or two of R code, while solving your problem, and become much 
more readable if we know what it's supposed to do.



More information about the R-help mailing list