"hey"
, "I'm a string"
) in either single or double quotesTRUE
or FALSE
- all capital letters and are not in quotes.vector
- 1-dimensional object of one class (all numeric or all character)matrix
- 2-dimensional object of one classdata.frame
- 2-dimensional object, can be multiple classes (like Excel spreadsheet)array
- object of > 2 dimensions of one class. The data in a nifti
object is one of these (usually 3-D)c()
to create a vector of numeric values:v = c(1, 4, 3, 7, 8) print(v)
[1] 1 4 3 7 8
w = 1:5 print(w)
[1] 1 2 3 4 5
The gray boxes denote code, and the lines after denote the output.
In R
, you can assign using the equals =
or arrow <-
(aka assigment operator).
The above commands are equivalent to:
w = 1:5 w <- 1:5
There are no differences in these 2 commands, but just preference (we use =
).
Variable/object names:
$
, quotes, or other special characters
.
) and underscores _
?
symbol before the name of the function. This is a shortcut for the help
command:c
:?c help(topic = "c")
??
or help.search
:??c help.search(pattern = "c")
y
and Y
are different)#
to commentYou can also be explicit about which package you are using with the ::
operator, where the syntax is package::function()
:
utils::help("c")
m
m = matrix(1:12, nrow = 3) print(m)
[,1] [,2] [,3] [,4] [1,] 1 4 7 10 [2,] 2 5 8 11 [3,] 3 6 9 12
a
a = array(1:36, dim = c(3, 4, 3))
dim()
function returns the dimensions of the arraydim(a)
[1] 3 4 3
1
, not zero):print(v)
[1] 1 4 3 7 8
print(v[4])
[1] 7
print(v[1:3])
[1] 1 4 3
print(v[c(1,3,5)])
[1] 1 3 8
[row,column]
format,print(m[1,3])
[1] 7
print(m[1:2,3:4])
[,1] [,2] [1,] 7 10 [2,] 8 11
row
or column
missing then all values printed:print(m[,4])
[1] 10 11 12
print(m[2,])
[1] 2 5 8 11
[x,y,z]
format:print(a[1,1,1])
[1] 1
dim(a[,4,])
[1] 3 3
This will return an error - need to specify all dims:
a[,4]
+
, -
, *
, /
, ^
- exponentslog
, abs
, sqrt
print(v); print(w)
[1] 1 4 3 7 8
[1] 1 2 3 4 5
print(v + 4)
[1] 5 8 7 11 12
print(v + w)
[1] 2 6 6 11 13
print(sqrt(w^2))
[1] 1 2 3 4 5
>
, >=
, <
, <=
, ==
(equals), !=
(not equal)!
- not, &
- and, |
- or (a “pipe”)all()
: function to test all values TRUE
and any()
: (are any)print(!FALSE)
[1] TRUE
print(TRUE | FALSE)
[1] TRUE
print(FALSE & FALSE)
[1] FALSE
c(all(c(TRUE, FALSE)), any(c(TRUE, FALSE)))
[1] FALSE TRUE
The which
command takes a logical and gets the indices of TRUE
:
which(v > 5)
[1] 4 5
v[ which(v > 5) ]
[1] 7 8
Or directly pass in a vector of logicals to subset:
v[ v > 5 ]
[1] 7 8
This method will be useful later when we are working with images.