You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: CodeTricks.md
+39-4
Original file line number
Diff line number
Diff line change
@@ -14,10 +14,10 @@ Matlab
14
14
* Use the matlab profiler
15
15
16
16
R
17
-
-
18
-
* R profiler: Rprof (functionalize your code first)
19
-
* sapply instead of for loops
17
+
-----
20
18
19
+
* R profiler: Rprof (functionalize your code first)
20
+
* sapply instead of for loops
21
21
22
22
23
23
Did you know, in R:
@@ -36,10 +36,34 @@ and `a^2 ` is slower than `a*a`.
36
36
37
37
Radford Neal [pointed this out](http://radfordneal.wordpress.com/2010/08/19/speeding-up-parentheses-and-lots-more-in-r/) in R-2.11.1, try testing in R 2.14.1 first.
38
38
39
-
Also, although many matrix operations can be performed on `data.frame`, they are _much_ faster when performed on `matrix` data types[^dfmat].
39
+
## Names and speed
40
+
41
+
Although many matrix operations can be performed on `data.frame`, they are _much_ faster when performed on `matrix` data types[^dfmat].
40
42
41
43
[^dfmat]: need a small example of this
42
44
45
+
Accesssing arrays via index is faster than by name, but using names can make for more readable code.
46
+
To achieve fast access and still use names, one can construct an environment that uses a hash table for lookup
47
+
48
+
```R
49
+
labeled.environment<-function(n) {
50
+
e<- new.env(hash=TRUE,size=n)
51
+
from<-"0123456789"
52
+
to<-"ABCDEFGHIJ"
53
+
for (iin1:n) {
54
+
assign(x=chartr(from,to,i), value=i, envir=e)
55
+
}
56
+
e
57
+
}
58
+
e.20<- labeled.environment(20)
59
+
60
+
## Access via
61
+
e.20[["B"]]
62
+
get("BH", env=e.20)
63
+
```
64
+
65
+
This tip is from [Joseph Adler](http://broadcast.oreilly.com/2010/03/lookup-performance-in-r.html)
66
+
43
67
44
68
## Compiling code
45
69
@@ -48,3 +72,14 @@ As of `R` 2.13, the `compiler` package lets you compile code into byte for faste
48
72
`compiled.function <- cmpfun(orig.function)`
49
73
50
74
A demonstration [here](http://dirk.eddelbuettel.com/blog/2011/04/12/) shows that it speeds some basic functions up about 4X.
0 commit comments