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

From: Erik Iverson <eriki_at_ccbr.umn.edu>
Date: Mon, 14 Jun 2010 15:36:46 -0500

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.



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. Received on Mon 14 Jun 2010 - 20:39:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 14 Jun 2010 - 20:40:42 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive