Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 31st, 2012  |  syntax: None  |  size: 0.80 KB  |  hits: 14  |  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. Generate vectors using R
  2. (1,1);(0,2);(2,0)
  3.        
  4. A=2
  5. B=3
  6. C=2
  7.  
  8. myfun <- function(a=A, b=B, c=C) {
  9.   out <- do.call(expand.grid, lapply(1:a, function(x) 0:b))
  10.   return(out[rowSums(out)==c,])
  11. }
  12.  
  13. > out[rowSums(out)==c,]
  14.   Var1 Var2
  15. 3    2    0
  16. 6    1    1
  17. 9    0    2
  18.        
  19. z <- expand.grid(0:3,0:3)
  20. z[rowSums(z)==2, ]
  21.   Var1 Var2
  22. 3    2    0
  23. 5    1    1
  24. 7    0    2
  25.        
  26. z <- expand.grid( rep( list(C), A) )
  27.        
  28. > z <- expand.grid(rep(list(0:3), 3))
  29. > z[rowSums(z)==2, ]
  30.    Var1 Var2 Var3
  31. 3     2    0    0
  32. 6     1    1    0
  33. 9     0    2    0
  34. 18    1    0    1
  35. 21    0    1    1
  36. 33    0    0    2
  37.        
  38. library(partitions)
  39.  
  40. A <- 2
  41. B <- 5
  42. C <- 7
  43.  
  44. comps <- t(compositions(C, A))
  45. ii <- apply(comps, 1, FUN=function(X) all(X %in% 0:B))
  46. comps[ii, ]
  47. #      [,1] [,2]
  48. # [1,]    5    2
  49. # [2,]    4    3
  50. # [3,]    3    4
  51. # [4,]    2    5