天才是用勞動換來的?!谥?/p>
1. if條件語句
- 基礎(chǔ)語法
#if(一個邏輯值,不可以是多個邏輯值組成的向量){代碼} #TRUE就運行,F(xiàn)ALSE就不運行
# if(F){...} 則{}里的代碼被跳過;
# if(T){...} 則{}里的代碼被運行。
- {}的代碼,可以被折疊
- 代碼習(xí)慣:全選運行
- source() 在不打開腳本的情況下直接運行腳本
- if…else…
#1\. if...else...
I =1
if (i>0){
print('+')
} else {
print("-")
}
## [1] "+"
#2\. ifelse(x, yes, no)
# x: 邏輯值或者邏輯值向量
# yes: 邏輯值為TRUE時的返回值
# no: 邏輯值為FALSE時的返回值
i = 1
ifelse(i>0,"+","-")
## [1] "+"
x = rnorm(3)
x
## [1] -0.5026486 1.0311586 1.0098103
ifelse(x>0,"+","-")
## [1] "-" "+" "+"
- ifelse()+str_detect()
library(stringr)
samples = c("tumor1","tumor2","tumor3","normal1","normal2","normal3")
k1 = str_detect(samples,"tumor");k1
## [1] TRUE TRUE TRUE FALSE FALSE FALSE
ifelse(k1,"tumor","normal")
## [1] "tumor" "tumor" "tumor" "normal" "normal" "normal"
k2 = str_detect(samples,"normal");k2
## [1] FALSE FALSE FALSE TRUE TRUE TRUE
ifelse(k2,"normal","tumor")
## [1] "tumor" "tumor" "tumor" "normal" "normal" "normal"
- 多個條件
i = 0
if (i>0){
print('+')
} else if (i==0) {
print('0')
} else if (i< 0){
print('-')
}
## [1] "0"
ifelse(i>0,"+",ifelse(i<0,"-","0"))
## [1] "0"
2. 長腳本管理方式
分成多個腳本,每個腳本最后保存Rdata,下一個腳本開頭清空再加載
#上一個腳本
#save(pd,exp,gpl,file="step1output.Rdata")
#下一個腳本
rm(list = ls())
#load(file = "step1output.Rdata") 不需要重復(fù)運行限速步驟,推薦用Rdata保存數(shù)據(jù)
3. 項目的組織方式
- 在同一個工作目錄下
- 工作目錄的下一級文件夾
#當(dāng)工作目錄中存在子文件夾,比如名為xiaokaixin的文件夾,打開里面的soft文件
#read.csv("xiaokaixin/soft.csv")
#同樣地,也可以在子文件夾保存文件
#save(x,file="xiaokaixin/x.Rdata")
- 工作目錄的上一級文件夾
#load(../xx/xx.Rdata) "../"上一級
#load(../../xx/xx.Rdata) 上上級
4. 條件語句case_when
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
i = 0
case_when(i > 0 ~ "+",
i < 0 ~ "-",
T ~ "0")
## [1] "0"
?ggpubr::stat_compare_means
補充: ns: p > 0.05 *: p <= 0.05 **: p <= 0.01 ***: p <= 0.001 ****: p <= 0.0001
5. for循環(huán)
對x里的每個元素i進(jìn)行同一操作,根據(jù)x的元素個數(shù)決定循環(huán)次數(shù)
for( i in 1:4){
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
#批量畫圖
par(mfrow = c(2,2)) #切分畫板,兩行兩列
for(i in 1:4){
plot(iris[,i],col = iris[,5]) #col = iris[,5],決定顏色
}

#批量裝包
pks = c("tidyr","dplyr","stringr")
for(g in pks){ #x,這里是pks需要提前定義,g或者i不需要提前定義
if(!require(g,character.only = T)) #循環(huán)時需要加上character.only = T
install.packages(g,ask = F,update = F) #循環(huán)時不要提問和更新
}
代碼來源于生信技能樹 小潔老師??