I have a data.frame y as below, and I want to calculate the "weighted modal
value", where v... are the values, and w... are the weights.
At tha moment I am doing it as shown below, but my data.frame has 165900 and
more rows, and it takes ages to do the calculations. I am sure there is a
much better way.

Can somebody help me in this regard?

Thanks,

Rainer


>  y
       v1 v2 v3 w1 w2 w3
158726  3  3  3  7  7  6
158727  3  3  3  7  7  6
158728  3  3  3  7  7  6
158729  3  3  3  7  7  6
158730 NA NA NA NA NA NA
158731 NA NA NA NA NA NA
>
p <- apply(
               y,
               1,
               function(x) {
                 if (sum(is.na(x))==length(x)) {
                   return(NA)
                 } else {
                   result <- aggregate(
                                       as.numeric(x[4:6]),
                                       list(as.numeric(x[1:3])),
                                       sum)
                   result <- result[[1]][which.max(result[[2]])]
                   return(result)
                 }
               }
               )
> p
158726 158727 158728 158729 158730 158731
     3      3      3      3     NA     NA
>




-- 
Rainer M. Krug, Centre of Excellence for Invasion Biology, Stellenbosch
University, South Africa

        [[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