Day 1 R語言再復習

第一天要學會這10題:http://www.bio-info-trainee.com/3750.html

導入文件為Factor時,想轉(zhuǎn)化為character時。這句話不能很少

options(stringsAsFactors = F)

安裝R包就一下幾句命令都試一下就好,包要區(qū)分大小寫

##方法一
source("http://bioconductor.org/biocLite.R")
options(BioC_mirror="http://mirrors.ustc.edu.cn/bioc/")
BiocInstaller::biocLite('xCell')  #########這一種方法安裝也失敗了
########## BioC_mirror: http://bioconductor.org
##方法二
if (!requireNamespace("BiocManager"))
    install.packages("BiocManager")
BiocManager::install()
##方法三
install.packages('xCell')
##方法四
install_github("ebecht/MCPcounter",ref="master", subdir="Source")

read.table有很多坑,碰到問題總是在從這里可以解決
csv格式以','分隔

a=read.table('e4-plot.txt',sep = '\t',fill = T,header = T哈街,comment.char = '!', header = T)####真實的表達矩陣
stringsAsFactors = F)####comment.char = '!',    去掉!開頭的頭文件荧恍!

ID轉(zhuǎn)換尋找到相應的注釋包,下載相應的包

options()$repos
options()$BioC_mirror 
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/")
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
BiocManager::install("請輸入自己找到的R包",ask = F,update = F)
options()$repos
options()$BioC_mirror

ID轉(zhuǎn)換乔询,ID轉(zhuǎn)來轉(zhuǎn)去這三句話就可以(基因ID,探針I(yè)D逢倍,Ensemble ID捧颅,Gene Symbol)

library(org.Hs.eg.db)
ls("package:org.Hs.eg.db")
g2s=toTable(org.Hs.egSYMBOL);head(g2s)
g2e=toTable(org.Hs.egENSEMBL);head(g2e)
tmp=merge(a,g2e,by='ensembl_id')
tmp=merge(tmp,g2s,by='gene_id')

文本處理,文字分隔牢記這一句話就夠了(使用lapply 或者stringr)

group_list=unlist(lapply(pd$title,function(x){ strsplit(x,' ')[[1]][4]}))
###如果不夠再補充幾句
####第一句
substring(temprary,1,3)
####第二句stringr 包輕松處理文本
library(stringr)
str_split(patient_ID, ",",simplify = T)[,2] #####stringr直接變成data 

grep篩選行

wax=a[grep('was', a[,1]),]
wax=a[grepl('was', a[,1]),]
was=a[a[,1]=='was',]

dplyr 行列篩選(select 篩選列较雕,filter篩選行碉哑,更改名字,%>%管道)

rename(tb, y = year)
filter(iris, Sepal.Length > 7)
# 根據(jù)名字選擇列
select(flights, year, month, day)
#######"Piping" with %>% makes code more readable, e.g.
iris %>%
group_by(Species) %>%
summarise(avg = mean(Sepal.Width)) %>%
arrange(avg)

data frame 選擇行亮蒋,選擇列篩選(match,%in%,merge)三駕馬車

######第一架馬車
library(hgu133a.db)
ids=toTable(hgu133aSYMBOL)
head(ids)
tmp1=merge(ids,a,by='probe_id')
tmp2=ids[match(a$probe_id,ids$probe_id),]
####第二架馬車%in%
ng='ACTR3B ANLN BAG1 BCL2 BIRC5 BLVRA CCNB1 CCNE1 CDC20 CDC6'
ng=strsplit(ng,' ')[[1]]
table(ng %in%  rownames(dat))
ng=ng[ng %in%  rownames(dat)]
dat=dat[ng,]
dat=log2(dat)
pheatmap::pheatmap(dat,scale = 'row')
####第三架馬車merge
merge
tmp=merge(a,g2e,by='ensembl_id')
tmp=merge(tmp,g2s,by='gene_id')

cbioportal 數(shù)據(jù)庫挖掘一文就夠

a=read.table('e4-plot.txt',sep = '\t',fill = T,header = T)
colnames(a)=c('id','subtype','expression','mut')
dat=a
library(ggstatsplot)
ggbetweenstats(data =dat, x = subtype,  y = expression)
library(ggplot2)
ggsave('plot-again-BRCA1-TCGA-BRCA-cbioportal.png')

生存曲線就這兩句
單基因生存分析 TCGA數(shù)據(jù)分析 網(wǎng)址 http://www.oncolnc.org/
找到TP53基因在TCGA數(shù)據(jù)庫的乳腺癌數(shù)據(jù)集的表達量分組看其是否影響生存

a=read.table('BRCA_7157_50_50.csv',sep = ',',fill = T,header = T)
dat=a
library(ggplot2)
library(survival)
library(survminer) 
table(dat$Status)
dat$Status=ifelse(dat$Status=='Dead',1,0)
sfit <- survfit(Surv(Days, Status)~Group, data=dat)
sfit
summary(sfit)
ggsurvplot(sfit, conf.int=F, pval=TRUE)
ggsave('survival_TP53_in_BRCA_TCGA.png')

下載GEO就這幾句

# 注意查看下載文件的大小扣典,檢查數(shù)據(jù) 
f='GSE24673_eSet.Rdata'
library(GEOquery)
# 這個包需要注意兩個配置,一般來說自動化的配置是足夠的慎玖。
if(!file.exists(f)){
  gset <- getGEO('GSE24673', destdir=".",
                 AnnotGPL = F,     ## 注釋文件
                 getGPL = F)       ## 平臺文件
  save(gset,file=f)   ## 保存到本地
}
load('GSE24673_eSet.Rdata')  ## 載入數(shù)據(jù)
class(gset)
length(gset)
class(gset[[1]])

熱圖如果想要出現(xiàn)臨床信息的注釋annotation 就要引入tmp的data.frame

a=gset[[1]]
dat=exprs(a)
dim(dat)
pd=pData(a)
group_list=c('rbc','rbc','rbc','rbn','rbn','rbn','rbc','rbc','rbc','normal','normal')
dat[1:4,1:4]
M=cor(dat)
pheatmap::pheatmap(M)
tmp=data.frame(g=group_list)
rownames(tmp)=colnames(M)
pheatmap::pheatmap(M,annotation_col = tmp)

limma差異表達

exprSet=dat
exprSet[1:4,1:4]
# DEG by limma 
suppressMessages(library(limma)) 
design <- model.matrix(~0+factor(group_list))
colnames(design)=levels(factor(group_list))
rownames(design)=colnames(exprSet)
design
contrast.matrix<-makeContrasts(paste0(unique(group_list),collapse = "-"),levels = design)
contrast.matrix<-makeContrasts("progres.-stable",levels = design)
contrast.matrix 
##這個矩陣聲明贮尖,我們要把progres.組跟stable進行差異分析比較
##step1
fit <- lmFit(exprSet,design)
##step2
fit2 <- contrasts.fit(fit, contrast.matrix) ##這一步很重要,大家可以自行看看效果
fit2 <- eBayes(fit2)  ## default no trend !!!
##eBayes() with trend=TRUE
##step3
tempOutput = topTable(fit2, coef=1, n=Inf)
nrDEG = na.omit(tempOutput) 
#write.csv(nrDEG2,"limma_notrend.results.csv",quote = F)
head(nrDEG)

選擇重復探針中表達量最大的一個

library(hgu133a.db)
ids=toTable(hgu133aSYMBOL)
head(ids)
dat=dat[ids$probe_id,]
dat[1:4,1:4] 
ids$median=apply(dat,1,median)
ids=ids[order(ids$symbol,ids$median,decreasing = T),]
ids=ids[!duplicated(ids$symbol),]
dat=dat[ids$probe_id,]
rownames(dat)=ids$symbol
dat[1:4,1:4]  
dim(dat)

熱圖畫差異表達最明顯的50個基因還可以用scale參數(shù)矯正離群值

####apply函數(shù)實戰(zhàn)
apply(e,2,mean) ###2是列的意思
apply(head(e),1,mean)#####1是行的意思
boxplot(apply(dat,1,mad))
pheatmap::pheatmap(dat[order(apply(dat,1,mad), decreasing = T)[1:50],])
pheatmap::pheatmap(dat[order(apply(dat,1,mad), decreasing = F)[1:50],])
####也可以寫成這樣的
boxplot(apply(dat,1,mad))
cg=order(apply(dat,1,mad), decreasing = T)[1:50]
tmp=data.frame(g=group_list)
rownames(tmp)=colnames(dat)
pheatmap::pheatmap(dat[cg,],annotation_col = tmp)

繪制相關系數(shù)的熱圖趁怔。(文獻中經(jīng)吃毒耍可將)

library(corrplot) 
M <- cor( dat ) 
ac=data.frame(g=group_list)
rownames(ac)=colnames(M) 
pheatmap::pheatmap(M,show_colnames =F,show_rownames = F,
         annotation_col=ac,filename = 'heatmap_cor.png')

主成分分析

  library("FactoMineR")
  library("factoextra") 

  dat.pca <- PCA(dat[,-ncol(dat)], graph = FALSE)
  fviz_pca_ind(dat.pca,
               geom.ind = c("point", "text"), # show points only (nbut not "text")
               col.ind = dat$group_list, # color by groups
               palette = c("#00AFBB", "#E7B800"),
               addEllipses = TRUE, # Concentration ellipses
               legend.title = "Groups"
  )
  ggsave('all_samples_PCA.png')

對表達矩陣取對數(shù)

expr<- log2(expr+1)

對數(shù)據(jù)進行分組

dt <- read.delim(text =
                   '
pcode name gdp
53 云南 1.2815
54 西藏 0.0921
61 陜西 1.7689
62 甘肅 0.6837
63 青海 0.2301
64 寧夏 0.2752
1 hangzhou 0.2
65 新疆 0.9264', sep=' ', header=T)

dt_1 <- dt %>%
  arrange(desc(gdp)) %>%
  mutate(class=c(rep(c(1,2,3), each=2),2,3)) ######先排序后分組,因為與共是8個不是3的倍數(shù)痕钢,最后2和3的意思是將余數(shù)放到哪里
# 正態(tài)性檢驗
shapiro.test(dt_1$gdp)
# 方差分析
gdp_aov <- aov(gdp~class, dt_1)
summary(gdp_aov)

# Kruskal-Wallis檢驗
kruskal.test(gdp~class, dt_1)
!is.na()的用法
list <- read_excel("C:/Users/chenyuqiao/Desktop/胸外/免疫二區(qū)雜志list.xlsx")
list<- list[list$ISSN!= 'NA',]
list<- list[!is.na(list$ISSN) ,]  #############
write.csv(list, file = 'magzine_list.csv')
getwd()
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市序六,隨后出現(xiàn)的幾起案子任连,更是在濱河造成了極大的恐慌,老刑警劉巖例诀,帶你破解...
    沈念sama閱讀 223,002評論 6 519
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件随抠,死亡現(xiàn)場離奇詭異裁着,居然都是意外死亡,警方通過查閱死者的電腦和手機拱她,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,357評論 3 400
  • 文/潘曉璐 我一進店門二驰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人秉沼,你說我怎么就攤上這事桶雀。” “怎么了唬复?”我有些...
    開封第一講書人閱讀 169,787評論 0 365
  • 文/不壞的土叔 我叫張陵矗积,是天一觀的道長。 經(jīng)常有香客問我敞咧,道長棘捣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,237評論 1 300
  • 正文 為了忘掉前任休建,我火速辦了婚禮乍恐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘测砂。我一直安慰自己茵烈,他們只是感情好,可當我...
    茶點故事閱讀 69,237評論 6 398
  • 文/花漫 我一把揭開白布邑彪。 她就那樣靜靜地躺著瞧毙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪寄症。 梳的紋絲不亂的頭發(fā)上宙彪,一...
    開封第一講書人閱讀 52,821評論 1 314
  • 那天,我揣著相機與錄音有巧,去河邊找鬼释漆。 笑死,一個胖子當著我的面吹牛篮迎,可吹牛的內(nèi)容都是我干的男图。 我是一名探鬼主播,決...
    沈念sama閱讀 41,236評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼甜橱,長吁一口氣:“原來是場噩夢啊……” “哼逊笆!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起岂傲,我...
    開封第一講書人閱讀 40,196評論 0 277
  • 序言:老撾萬榮一對情侶失蹤难裆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體乃戈,經(jīng)...
    沈念sama閱讀 46,716評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡褂痰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,794評論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了症虑。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缩歪。...
    茶點故事閱讀 40,928評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖谍憔,靈堂內(nèi)的尸體忽然破棺而出匪蝙,到底是詐尸還是另有隱情,我是刑警寧澤韵卤,帶...
    沈念sama閱讀 36,583評論 5 351
  • 正文 年R本政府宣布骗污,位于F島的核電站,受9級特大地震影響沈条,放射性物質(zhì)發(fā)生泄漏需忿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,264評論 3 336
  • 文/蒙蒙 一蜡歹、第九天 我趴在偏房一處隱蔽的房頂上張望屋厘。 院中可真熱鬧,春花似錦月而、人聲如沸汗洒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,755評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽溢谤。三九已至,卻和暖如春憨攒,著一層夾襖步出監(jiān)牢的瞬間世杀,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,869評論 1 274
  • 我被黑心中介騙來泰國打工肝集, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瞻坝,地道東北人。 一個月前我還...
    沈念sama閱讀 49,378評論 3 379
  • 正文 我出身青樓杏瞻,卻偏偏與公主長得像所刀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子捞挥,可洞房花燭夜當晚...
    茶點故事閱讀 45,937評論 2 361

推薦閱讀更多精彩內(nèi)容