x y
1 1 a
2 2 b
3 3 c
IOC-R Week 4
<-
, ->
, =
Element-wise comparison: ==
, !=
, >
, <
, >=
, <=
, return logical results.
Element-wise comparison: NOT (!
), AND (&
), OR (|
), etc., returns logical values.
%in%
OperatorWe use %in%
to check if left-side values are present in right-side, it returns logical values.
any()
, all()
and which()
Given a set of logical vectors:
any()
: is at least one of the values TRUE
?all()
: are all of the values TRUE
?which()
: return indices of TRUE
values.We have a vector log2FoldChange <- c(1.2, -0.5, 0.9, 0.7, -1.1)
, what are the expected results for the following codes?
which(log2FoldChange > 0.8)
any(log2FoldChange > 0.8)
all(log2FoldChange > 0)
Conditional statements allow us to make decisions based on logical conditions, guiding how the code behaves in different scenarios.
flowchart LR A{temperature > 37} --> B(TRUE) A --> C(FALSE) B --> D[Fever] C --> E[Normal]
flowchart LR A{log2FC > 0} --> B(TRUE) A --> C(FALSE) B --> D[Up-regulated] C --> E[Not up-regulated]
if
and if else
Syntax:
if
without else
but never in the opposite way.TRUE
or FALSE
) and cannot be NA.flowchart LR A{log2FC > 0} --> B(TRUE) A --> C(FALSE) B --> D[Up-regulated] C --> E[Not up-regulated]
log2FC <- 2.5
if (log2FC > 0) {
# code to run if condition is TRUE
print("Up-regulated")
} else {
# code to run if condition is FALSE
print("Not up-regulated")
}
[1] "Up-regulated"
What will you get when log2FC
is 0?
[1] "Not up-regulated"
ifelse()
FunctionSyntax:
Example:
[1] "Not up-regulated"
Functions = Reusable blocks of code.
Call a function: write function name followed by ()
, including any required arguments inside ()
.
Use ?
or help()
to view the function’s documentation, e.g.: ?mean
, help(mean)
Syntax:
function()
and argument(s).{}
frame the function body.return()
(usually) at the end will return a result.A function can have 0, 1 or multiple parameters, with or without default values.
Example: a function to calculate geometric mean1.