Pastebin launched a little side project called HostCabi.net, check it out ;-)Pastebin is 300% more awesome when you are logged in. Sign Up, it's FREE!
Guest

Untitled

By: a guest on Dec 4th, 2012  |  syntax: None  |  size: 1.38 KB  |  hits: 24  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. p <-with(mtcars,tapply(carb,list(cyl,vs),length))
  2. prop.table(p,2) # by column
  3.        
  4. p <- with(mtcars,tapply(carb,list(cyl,vs,gear),length))
  5.        
  6. test <- 1:8
  7. dim(test) <- c(2,2,2)
  8. test
  9. , , 1
  10.  
  11.      [,1] [,2]
  12. [1,]    1    3
  13. [2,]    2    4
  14.  
  15. , , 2
  16.  
  17.      [,1] [,2]
  18. [1,]    5    7
  19. [2,]    6    8
  20.        
  21. # % of all values in each stratum/sub-table
  22. prop.table(test,3)
  23.  
  24. # row % within each stratum/sub-table
  25. prop.table(test,c(3,1))
  26.  
  27. # column % within each stratum/sub-table
  28. prop.table(test,c(3,2))
  29.        
  30. # set one of the values to NA as an example
  31. test[7] <- NA
  32.  
  33. # do the procedure
  34. nas <- is.na(test)
  35. test[nas] <- 0
  36. result <- prop.table(test,c(3,2))
  37. result[nas] <- NA
  38.  
  39. result
  40. , , 1
  41.  
  42.           [,1]      [,2]
  43. [1,] 0.3333333 0.4285714
  44. [2,] 0.6666667 0.5714286
  45.  
  46. , , 2
  47.  
  48.           [,1] [,2]
  49. [1,] 0.4545455   NA
  50. [2,] 0.5454545    1
  51.        
  52. library(reshape2)
  53. tables  <- acast(mtcars, cyl~vs~gear,value.var = 'carb', fun.aggregate = 'length')
  54.  tables
  55. , , 3
  56.  
  57.    0 1
  58. 4  0 1
  59. 6  0 2
  60. 8 12 0
  61.  
  62. , , 4
  63.  
  64.   0 1
  65. 4 0 8
  66. 6 2 2
  67. 8 0 0
  68.  
  69. , , 5
  70.  
  71.   0 1
  72. 4 1 1
  73. 6 1 0
  74. 8 2 0
  75.  
  76. prop.table(tables, 2:3)
  77.  
  78. , , 3
  79.  
  80.   0         1
  81. 4 0 0.3333333
  82. 6 0 0.6666667
  83. 8 1 0.0000000
  84.  
  85. , , 4
  86.  
  87.   0   1
  88. 4 0 0.8
  89. 6 1 0.2
  90. 8 0 0.0
  91.  
  92. , , 5
  93.  
  94.      0 1
  95. 4 0.25 1
  96. 6 0.25 0
  97. 8 0.50 0
  98.        
  99. with(mtcars,table(cyl, vs ,gear))
  100.  
  101. , , gear = 3
  102.  
  103.    vs
  104. cyl  0  1
  105.   4  0  1
  106.   6  0  2
  107.   8 12  0
  108.  
  109. , , gear = 4
  110.  
  111.    vs
  112. cyl  0  1
  113.   4  0  8
  114.   6  2  2
  115.   8  0  0
  116.  
  117. , , gear = 5
  118.  
  119.    vs
  120. cyl  0  1
  121.   4  1  1
  122.   6  1  0
  123.   8  2  0