-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathREADME.Rmd
129 lines (98 loc) · 2.38 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# Some R gotchas
Some potentially surprising results from R functions
which are important to be aware of.
[Here](http://stackoverflow.com/questions/1535021/whats-the-biggest-r-gotcha-youve-run-across)
is a stackoverflow discussion with some more.
Even more: [R programming for those coming from other languages](http://www.johndcook.com/R_language_for_programmers.html)
And more: [aRrgh: a newcomer's (angry) guide to R](http://tim-smith.us/arrgh/index.html)
### Dropped dimensions
For matrix:
```{r}
m <- matrix(1:6, ncol=3)
m
m[1,] # vector
m[,1] # vector
m[1,,drop=FALSE] # matrix
```
For data.frame:
```{r}
df <- data.frame(a=1:3,b=4:6)
df
df[1,] # data.frame
df[,1] # vector
df[,1,drop=FALSE] # data.frame
```
### stringsAsFactors: data.frame and read.table
```{r}
df <- data.frame(a=c("10","11","12"))
as.numeric(df$a) + 1
df <- data.frame(a=c("10","11","12"), stringsAsFactors=FALSE)
as.numeric(df$a) + 1
```
### Conventions, not so much
boxplot: `names` & `horizontal`
barplot: `names.arg` & `horiz`
stripchart: `group.names` & `vertical`
### Logical operators
```{r}
c(TRUE,TRUE,FALSE) & c(FALSE,TRUE,TRUE) # element-wise
c(TRUE,TRUE,FALSE) && c(FALSE,TRUE,TRUE) # just the first
x <- "hi"
is.numeric(x) && x + 1 # evaluates left to right
is.numeric(x) & x + 1 # produces error
```
### apply returns columns
```{r}
m <- matrix(1:6, ncol=3)
m^2
apply(m, 2, `^`, 2) # column-wise, ok
apply(m, 1, `^`, 2) # gives back row-wise operation as columns
```
### Column names restricted characters
```{r}
df <- data.frame("test-it-#1"=1:2)
df
make.names("test-it-#1") # this function is used
```
### Removing columns by name
```{r}
df <- data.frame(a=1:2,b=3:4,c=5:6,d=7:8)
df[,-(2:3)] # numeric index ok
df[,-c("b","c")] # not character index
subset(df, select=-c(b,c)) # by name works here
```
### Safer to use seq_along and seq_len
```{r}
x <- numeric(0)
1:length(x)
seq_len(length(x))
seq_along(x)
```
### is.na and is.null
```{r}
x <- c(1,2,NA)
which(x == NA)
which(is.na(x))
y <- NULL
y == NULL
is.null(y)
```
### write.csv and read.csv don't agree
```{r}
m <- matrix(1:4,ncol=2)
write.csv(m,file="matrix.csv")
read.csv("matrix.csv")
read.csv("matrix.csv",row.names=1)
```
```{r,echo=FALSE,results="hide"}
file.remove("matrix.csv")
```
### Formulas save variables in environment even if not referenced
```{r}
f <- function() {
y <- 1:10
form <- ~ 1
form
}
get("y", environment(f()))
```