专题3 条件和循环

2024-04-18 13:42:47 浏览数 (1)

条件和循环

一.条件语句

###1.if(){ }如果(逻辑值,不是逻辑值向量)就{}

(1)只有if没有else,那么条件是FALSE时就什么都不做 可以用于管理代码块
代码语言:r复制
i = -1
if (i<0) print('up')
代码语言:2复制
## [1] "up"
代码语言:r复制
if (i>0) print('up')

#理解下面代码
if(!require(tidyr)) install.packages('tidyr')
(2)有else
代码语言:r复制
i =1
if (i>0){
  print(' ')
} else {
  print("-")
}
代码语言:r复制
## [1] " "
重点:ifelse
代码语言:r复制
i = 1
ifelse(i>0," ","-")
代码语言:r复制
## [1] " "
代码语言:r复制
x = rnorm(3) # 可以是逻辑值或逻辑值向量
x
代码语言:r复制
## [1] -0.7623049  0.9558385  2.0604772
代码语言:r复制
ifelse(x>0," ","-")
代码语言:r复制
## [1] "-" " " " "
ifelse() str_detect(),王炸
代码语言:r复制
library(stringr)

samples = c("tumor1","tumor2","tumor3","normal1","normal2","normal3")
k1 = str_detect(samples,"tumor");k1
代码语言:r复制
## [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE
代码语言:r复制
ifelse(k1,"tumor","normal")
代码语言:r复制
## [1] "tumor"  "tumor"  "tumor"  "normal" "normal" "normal"
代码语言:r复制
k2 = str_detect(samples,"normal");k2
代码语言:r复制
## [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE
代码语言:r复制
ifelse(k2,"normal","tumor")
代码语言:r复制
## [1] "tumor"  "tumor"  "tumor"  "normal" "normal" "normal"
(3)多个条件
代码语言:r复制
i = 0
if (i>0){
  print(' ')
} else if (i==0) {
  print('0')
} else if (i< 0){
  print('-')
}
代码语言:r复制
## [1] "0"
代码语言:r复制
ifelse(i>0," ",ifelse(i<0,"-","0"))
代码语言:r复制
## [1] "0"

二、for循环

代码语言:r复制
for( i in 1:4){
  print(i)
}
代码语言:r复制
## [1] 1
## [1] 2
## [1] 3
## [1] 4

批量画图

代码语言:r复制
par(mfrow = c(2,2))
for(i in 1:4){
  plot(iris[,i],col = iris[,5])
}

批量装包

代码语言:r复制
pks = c("tidyr","dplyr","stringr")
for(g in pks){
  if(!require(g,character.only = T))
    install.packages(g,ask = F,update = F)
}
dplyr包中case_when简化ifelse
代码语言:r复制
library(dplyr)
# case_when() # 可用于将数据转换为分类因子

df <- data.frame(player = c('AJ', 'Bob', 'Chad', 'Dan', 'Eric', 'Frank'),
                 position = c('G', 'F', 'F', 'G', 'C', NA),
                 points = c(12, 15, 19, 22, 32, NA),
                 assists = c(5, 7, 7, 12, 11, NA))
df
代码语言:r复制
##   player position points assists
## 1     AJ        G     12       5
## 2    Bob        F     15       7
## 3   Chad        F     19       7
## 4    Dan        G     22      12
## 5   Eric        C     32      11
## 6  Frank     <NA>     NA      NA
代码语言:r复制
df %>%
  mutate(quality = case_when(points > 20 ~ 'high',
                             points > 15 ~ 'med',
                             TRUE ~ 'low' ))
代码语言:r复制
##   player position points assists quality
## 1     AJ        G     12       5     low
## 2    Bob        F     15       7     low
## 3   Chad        F     19       7     med
## 4    Dan        G     22      12    high
## 5   Eric        C     32      11    high
## 6  Frank     <NA>     NA      NA     low

引用自生信技能树

0 人点赞