Advertisement
celestialgod

mode

Aug 3rd, 2015
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.67 KB | None | 0 0
  1. library(plyr)
  2. mat = t(replicate(3,sample(as.character(1:3),100,replace=T)))
  3. DF = data.frame(mat, stringsAsFactors = FALSE)
  4. DF = colwise(factor, levels = as.character(1:3))(DT)
  5. mode_f = function(v){
  6.   tv <- tabulate(v)
  7.   if (sum(tv == max(tv)) > 1){
  8.     NA
  9.   } else {
  10.     levels(v)[which.max(tv)]
  11.   }
  12. }
  13. new_sample = as.character(colwise(mode_f)(DF))
  14. na_loc = which(new_sample == "NA")
  15. for (j in na_loc){
  16.   distance = rowSums(sweep(as.matrix(DF[,1:(j-1)]), 2, new_sample[1:(j-1)], '=='))
  17.   if (sum(distance == min(distance)) > 1){
  18.     new_sample[j] = DF[sample(which(distance == min(distance)), 1),j]
  19.   } else {
  20.     new_sample[j] = DF[which.min(distance),j]
  21.   }
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement