i reading textbook named "an introduction r" , gives me example totally cannot understand.
the examples states
as artificial cute example, consider determinants of 2 2 matrices [a, b; c, d] each entry non-negative integer in range 0, 1, . . . , 9, digit. problem find determinants, ad − bc, of possible matrices of form , represent frequency each value occurs high density plot. amounts finding probability distribution of determinant if each digit chosen independently , uniformly @ random.
and provides code:
d <- outer(0:9, 0:9) fr <- table(outer(d, d, "-")) plot(as.numeric(names(fr)), fr, type="h", xlab="determinant", ylab="frequency")
i know first line doing have no idea "-" sign in outer() function , table() in case. also, why use name() function in last plot() function
perhaps should explain small example first. let's suppose want find distribution of determinant ad - bc
, a, b, c, d
either 0 or 1.
the first line
product <- outer(0:1, 0:1, "*") # [,1] [,2] #[1,] 0 0 #[2,] 0 1
computes possible outcomes of paired product, i.e.,
0 * 0 = 0 0 * 1 = 0 1 * 0 = 0 1 * 1 = 1
this maps possible outcomes of ad
, bc
in ad - bc
.
the second line:
minus <- outer(product, product, "-") , , 1, 1 [,1] [,2] [1,] 0 0 [2,] 0 1 , , 2, 1 [,1] [,2] [1,] 0 0 [2,] 0 1 , , 1, 2 [,1] [,2] [1,] 0 0 [2,] 0 1 , , 2, 2 [,1] [,2] [1,] -1 -1 [2,] -1 0
computes possible outcomes of ad - bc
. perhaps not easy read 4d array. how about:
minus <- as.numeric(minus) #[1] 0 0 0 1 0 0 0 1 0 0 0 1 -1 -1 -1 0
then time make contingency table of possible outcomes:
fr <- table(minus) #-1 0 1 # 3 10 3
finally, example code plot table.
what if solve problem
you felt difficult read result of outer
, every time apply outer
, dimension grows. example, applying outer
2 1d vectors results in 2d matrix, while further applying outer
2 2d matrices results in 4d array.
for easy-to-understand purpose, use as.numeric()
flatten result of outer
every time. use this:
product <- as.numeric(outer(0:1,0:1,"*")) #[1] 0 0 0 1 minus <- as.numeric(outer(product, product, "-")) #[1] 0 0 0 1 0 0 0 1 0 0 0 1 -1 -1 -1 0 plot(table(minus))
with original problem, do:
product <- as.numeric(outer(0:9,0:9,"*")) minus <- as.numeric(outer(product, product, "-")) plot(table(minus))
Comments
Post a Comment