This article is based on R 4.1.2.
1. ifelse & if/else
a. Identifying fulfilled conditions
-
all(condition)
• Returns TRUE if the condition is fulfilled by all elements
-
any(condition)
• Returns TRUE if the condition is fulfilled by at least one element
-
which(condition)
• Returns the position of the elements for which the condition is TRUE
q <- c(1, 2, 3, 4, 5, 6)
all (q >1 )
> [1] FALSE
any (q > 1)
[1] TRUE
which (q >1 )
[1] 2 3 4 5 6
b. ifelse
-
ifelse(test, yes, no)
- Very useful when the test is a logical test
- yes is the result if the test is TRUE
- no if it is FALSE
data$WTFLG <- ifelse(data$WT > 100, 2, 1)
# If more than two replacements are needed:
data$WTFLG <- ifelse(data$WT > 100, 2,
ifelse(data$WT > 70, 1, 0))
# Alternatively:
data$WTFLG[data$WT > 100] <- 2
data$WTFLG[data$WT > 70 & data$WT <= 100] <- 1
data$WTFLG[data$WT <= 70] <- 0
c. if/else
The if/else structure runs alternative code depending on input:
if(test){expression)
# Can be used alone or in combination with else{expression}:
if (any(is.na(data$DV))){
data$DV[is.na(data$DV)] <- -99
} else {
cat(”the dataset appears okay”)
}
d. ifelse 和 if/else 的区别
- if语句的条件是个TRUE/FALSE值,如果是个长度>1的逻辑向量,只判断第一个TRUE/FALSE值;而ifelse是长度任意的逻辑向量,返回根据逻辑向量对应对的yes/no值组合的新向量
- ifelse如果test的长度是1,而yes/no是长度>1的向量,也是返回长度为1的对应值。如果yes/no是list类型,则返回第一个元素。而if语句根据条件返回对应表达式的值。
# Example 1:
a = 0
b = c(1, 2, 3)
ifelse(a==0, b, 0)
if(a==0){b}else{0}
## results1:
> a = 0
> b = c(1, 2, 3)
> ifelse(a==0, b, 0)
[1] 1
> if(a==0){b}else{0}
[1] 1 2 3
# Example 2:
a = c(1, 2, 3)
b = 0
ifelse(a == c(1, 2, 3), 1, 0)
if(a==c(1, 2, 3)){1}else{0}
## results2:
> a = c(1, 2, 3)
> b = 0
> ifelse(a == c(1, 2, 3), 1, 0)
[1] 1 1 1
> if(a==c(1, 2, 3)){1}else{0}
[1] 1
Warning message:
In if (a == c(1, 2, 3)) { :
the condition has length > 1 and only the first element will be used
2. loops
a. for loop
- A for loop in R is made according to the structure:
for (variable in sequence){expression)
# This allows the expresssion to be run with the variable taking sequentially every value of the sequence such as:
> values <- seq(1, 100, by = 2)
> values_sq <- NULL
> for (i in 1:length(values) ) {
values_sq[i] <- values[i]^2
}
# for 条件里如果不写 1:length 写成length(),输出的结果前面全是NA,只有最后一个被平方
b. while loop
A while loop in R is made according to the structure:
while (condition){expression)
# Executes expression while condition is TRUE.
> x <- 1
> while (x < 5){
x <- x + 1
}
Caution: Beware of infinite loops.
3. Function writing
Creating a function is easy and can be done as:
fun <- function(list of arguments){function code}
# example
square_fun <- function(x){ print(x^2) }
for (i in 1:4) { square_fun(i) }
> [1] 1 4 9 16
NB:
(1) Objects created inside functions only exist in the function
fun <- function(x) {z <- 2 * x}
fun(4)
> [1] 8
z
> Error: object ‘z’ not found
# If object needed outside, use return():
fun <- function(x) {z <- 2 * x; return(z)}
z2 <- fun(4)
z2
> [1] 8
With multiple object returned, use list(): return(list(x,y))
while return (x, y)
is not allowed in R
(2) print messages from functions
Functions are “silent”, and Create return message using cat()
- makes pretty text and translates special characters
(e.g. \n adds a line break in a character string)
- used with paste() to generate interactive messages
fun <- function(x) {
z <- 2*x
cat(“Done!”)
return(z)
}
z6 <- fun(3)
> Done!
fun <- function(x) {
z <- 2*x
cat(paste(“The result is”, z))
return(z)
}
z6 <- fun(3)
> The result is 6
4. Apply
- Loops are really useful but slow and cumbersome in R
- Specific for R: the apply family (?apply)
-
- Applies functions repeatedly over rows/columns
- Different apply functions for different data structures:
-
- lapply, tapply, mapply, sapply, vapply …
- The dplyr package offers many additional functions which may
be easier and more intuitive to use compared to apply
详解:https://blog.csdn.net/weixin_45822007/article/details/116247858