-
Notifications
You must be signed in to change notification settings - Fork 5
/
0a. R basics quick review.r
104 lines (72 loc) · 2.11 KB
/
0a. R basics quick review.r
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
MyList <- list( A = 1:10
, B = 101:120
, C = 200:230
)
lapply(MyList, mean)
lapply(MyList, function(x) {
-2 * sd(x) + mean(x)
})
lapply(MyList, function(x) {
mn <- mean(x)
std <- sd(x)
c('-2SD'=mn-(2*std), Mean=mn, '+2SD'=mn+(2*std))
})
lapply(MyList, function(x) {
print("Hi, I am in a function!")
if (length(x) > 10) {
mn <- mean(x)
std <- sd(x)
c('-2SD'=mn-(2*std), Mean=mn, '+2SD'=mn+(2*std))
}
})
=============================
## a data.frame is simply a collection of lists
MyDF <- data.frame(A=1:10, B=11:20, C=21:30)
MyDF
lapply(MyDF, mean)
=============================
## binary operators
3 + 5
`+`(3, 5) # 3 + 5
`*`(3, 5) # 3 * 5
`==`(3, 5) # 3 == 5
`==`(5, 5) # 5 == 5
x <- 777
x
`<-`("x", 1:20) # x <- 1:20
x
## Backticks
##
## We can create functions with our own funky symbols
## Just use backticks (or quotes, if you prefer)
'7!:xKL3#$' <- function(x) {
cat("\nThis function is called '7!:xKL3#$'\nNotice we can even use hashes ('#')\nWhat a silly function... x is ", x, "\n\n")
}
`7!:xKL3#$`(23)
'7!:xKL3#$'(23)
"7!:xKL3#$"(23)
=============================
## Difference between NULL & NA
## (very) loosely speaking:
NULL : "It's like I dont exist"
NA : "I exist. But my value is missing, unknown or invalid"
Types of NA:
## NA is logical
is(NA)
## What if we want to specify, say, a string?
is(NA_character_)
## From the documentation:
?NA
"NA is a logical constant of length 1 which contains a missing value
indicator. NA can be coerced to any other vector type except raw.
There are also constants NA_integer_, NA_real_, NA_complex_ and
NA_character_ of the other atomic vector types which support missing
values: all of these are reserved words in the R language.
"
## To recap, the NA constants are:
NA_integer_
NA_real_
NA_complex_
NA_character_
## Question: Why is it 'NA_real_' and not 'NA_numeric_' ??
## Answer: Because this is open source.