title: "R_basic"
author: "Mande Xue"
date: "2020/4/14"
output:
html_document: default
(所有代码参考自生信宝典-R学习教程)
knitr::opts_chunk$set(echo = TRUE)
R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
#creat a vector
a <- c(rnorm(5), rnorm(5,1),runif(5),runif(5,-1,1),1:5, rep(0,5),c(2,10,11,13,4),scale(1:5)[1:5])
a
# ncol = 5 ,
# byrow = T, fill the matrix by row
a <- matrix(a, ncol = 5, byrow = T)
a
# 按行加和
# rowSums(a)
#去除全部为零的行
a <- a[rowSums(abs(a))!= 0,]
a
a*2
log2(abs(a)+1)
apply(a,2,var)
# 1 按行
# 2 按列
apply(a,1,mean)
b = a[apply(a,1,mean) > 0,]
b
# order函数 排序
# mad 中值绝对偏差
order(apply(b,1,mad),decreasing = T)
c = b[order(apply(b,1,mad),decreasing = T),]
c
# 添加行名
rownames(c) <- paste("Gene",letters[1:nrow(c)],sep = "_")
# 添加列名
colnames(c) <- toupper(letters[1:ncol(c)])
c
#转置
expr = t(c)
expr
#矩阵操作
expr2 =expr
expr2[expr2 < 0] = 0
expr2
expr2 <- as.data.frame(expr2)
str(expr2)
#利用列名当索引
expr2[expr2$Gene_c < 1 ,"Gene_b"]<-1
expr2
# 读入样品信息
sampleInfo = "Samp;Group;Genotype
A;Control;WT
B;Control;WT
D;Treatment;Mutant
C;Treatment;Mutant
E;Treatment;WT
F;Treatment;WT"
phenoData = read.table(text=sampleInfo,sep=";", header=T, row.names=1, quote="")
phenoData
# %in% 函数的过滤功能
phenoData = phenoData[rownames(phenoData) %in% rownames(expr),]
phenoData
# merge matrix
# by = 0,按行的名字排序
# by = columnname 按照共有的某一列合并
merge_data <- merge(expr,phenoData,by = 0, all.x = T)
merge_data
rownames(merge_data) <-merge_data$Row.names
merge_data
merge_data[,-1]
merge_data
merge_data[sapply(merge_data, is.numeric)]
网友评论