R语言实战(第二版)-part 1笔记

本文档详细介绍R语言的基础操作、数据管理及图形绘制技巧。涵盖了R语言环境配置、数据集创建、图形参数调整等内容,并提供了丰富的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


说明:
1.本笔记对《R语言实战》一书有选择性的进行记录,仅用于个人的查漏补缺
2.将完全掌握的以及无实战需求的知识点略去
3.代码直接在Rsudio中运行学习
---


R语言实战(第二版)

part 1 入门


----------第1章 R语言介绍--------------------

help.start() #帮助文档首页
demo() #R语言demo演示
demo(package = .packages(all.available = TRUE))
demo(image) #演示图像
example("mean") #函数mean使用示例

library(ggplot2);library(pheatmap)
example("ggplot") #演示R包
example("pheatmap") #par(ask=F)

vignette() #文档
vignette("dplyr")
options() #显示或设置当前选项
options(digits = 2)
help("option") #/help(options)

q() -> y #退出保存.Rhistory和.RData
dir.create("./test") #创建新目录
getwd()
ls() #列出对象
rm(list = ls()) #清空对象

save.image("./test.RData") #保存工作空间
load("./test.RData") #读取工作空间

source("./test.R") #执行脚本
pdf("test.pdf")
png("test.png")
dev.off()


library() #显示库中的包
.libPaths() #库路径
search() #显示哪些包已加载
help(package="ggplot2")
update.packages()

#R CMD BATCH <options> test.R test.Rout #Linux终端批处理
#<R/path/R.exe> CMD BATCH --vanilla --slave "test.R" #window 批处理

help(mtcars) #示例数据帮助
lmfit <- lm(mpg~wt, mtcars)
summary(lmfit)
plot(lmfit)
cook <- cooks.distance(lmfit)
plot(cook)
predict(lmfit,newdata)

----------第2章 创建数据集------------

#行列:observation-variable, record-field, example-attribute
#数值型变量,字符型变量;类别型(因子):有序,名义
#向量、矩阵、数组、数据框、因子、列表
matrix(1:20,nrow = 4,ncol = 5,byrow = F,dimnames = list(c("A","B","C","D"),c("math","eng","chinese","music","art")))
array(1:24,c(2,3,4),dimnames = list(c("A","B"),c("a","b","c"),c("test1","test2","test3","test4"))) #2行3列4维
#数据框选择列
mtcars[1:2]
mtcars[c("mpg","cyl")]
mtcars$mpg

#环境中有同名对象时不适用
attach(mtcars)
plot(mpg,wt)
detach(mtcars)

#赋值仅在with函数中有效
with(mtcars,{
  stats <- summary(mpg)
  out <<- summary(mpg) #使用特殊赋值符<<-可在括号外使用,写入全局变量,慎用
})
stats
out

#字符型向量因子水平默认以字母顺序创建,可用levels参数指定顺序
factor(c("poor","improved","excellent"),order=T)
factor(c("poor","improved","excellent"),order=T,levels = c("poor","improved","excellent"))
#数值型向量可编码为因子
factor(c(1,2),levels = c(1,2),labels = c("male","female"))

#列表元素
list[[2]]
list[["ages"]]
list$ages

#从键盘输入数据
data <- data.frame(age=numeric(0),gender=numeric(0),weight=numeric(0)) #创建空的数据框
data <- edit(data) #手动输入
data
newdata <- fix(data) #直接修改数据, 原data数据也将改变
newdata
data
newdata2 <- edit(data) #编辑并另存为数据,原data数据不会变
newdata2
data

read.table(colClasses = c("character"),row.names = "geneID",stringsAsFactors = F) 
#如读入以0开头的文本时保留0,如股票0010; 如若不以第一行为行名,指定某行; 默认转换字符变量为因子,设为F,可提升读取速度。
xlsx::read.xlsx("./test.xlsx",1) #1表工作表序号

#数据对象函数
length()
dim/str/class/mode
names()
cbind/rbind
head/tail

----------第3章 图形初阶--------------------

dev.new() #画图前新建一个图形窗口
plot(mtcars$mpg,mtcars$cyl)
dev.off() #关闭图形窗口,与pdf等连用

par(no.readonly = T,lty=2,pch=7) #设置图形参数

pch #点符号0-25
cex #符号大小
lty #线条类型1,2,3,4,5,6
lwd #线条宽度
col #默认的绘图颜色
col.axis  #坐标轴刻度文字颜色
col.lab #坐标轴名称颜色
col.main #标题颜色
col.sub #副标题颜色
fg #图形前景色
bg #图形背景色
cex.axis #坐标轴刻度文字缩放倍数
cex.lab #坐标轴名称缩放倍数
cex.main #标题缩放倍数
cex.sub #副标题缩放倍数
font #字体样式,1常规,2粗体,3斜体,4粗斜体,5符号字体
font.axis
font.lab
font.main
font.sub
ps #字体磅值
family #字体族,serif衬线,sans无衬线,mono等宽
pin #图形尺寸(宽高),英寸
mai #边界大小,下左上右,英寸
mar #边界大小,下左上右,英分


#表示颜色的方法:
col=1 #颜色下标
col="white" #名称
col="#FFFFFF" #十六进制
col=rgb(1,1,1) #RGB值(基于红绿蓝三色生成)
col=hsv(0,0,1) #HSV值(基于色相-饱和度-亮度生成)

colors() #查看所有颜色

library(RColorBrewer)
n <- 7
mycolors <- brewer.pal(n,"Set1") #Set1调色板中选取n种
barplot(rep(1,n),col = mycolors)

brewer.pal.info #调色板列表
display.brewer.all() #调色板展示

mycolors2 <- rainbow(n) #彩虹色
pie(rep(1,n),labels = mycolors2,col = mycolors2)

mygrays <- gray(0:n/n) #n阶灰度色
pie(rep(1,n),labels = mygrays,col = mygrays)

names(pdfFonts()) #系统中可用字体

abline(v=seq(1,10,2),lty=2,col="blue") #添加参考线
legend() #添加图例
text() #绘图区内部添加文本,通常用于标示图形中的点
mtext() #图形边界之一添加文本
plotmath() #添加数学符号
demo(plotmath)

#图形组合排布
par(mfrow=c(2,2)) #按行
par(mcol=c(1,3)) #按列
layout()

------------------第4章 基本数据管理------------

data <- data.frame(x1=c(2,2,6,4),x2=c(3,4,2,8))
transform(data,sumx=x1+x2,meanx=(x1+x2)/2)

x%%y #求余
4%%3
x%/%y #取整
5%/%2

is.na() #NA
is.infinite() #Inf,-Inf
is.nan() #NaN

#多数数值函数中含有na.rm=T参数
sum(x,na.rm = T)
na.omit()

Sys.Date()
date()
as.Date("2019-3-5")
as.Date("02/17/2019","%m/%d/%Y")
difftime(Sys.Date(),"2019-3-1",units = "days")

is.numeric()/is.character()/is.vector()/is.matrix()/is.data.frame()/is.factor()/is.logical() #判断,与if-then联合使用
as.numeric()/as.character()/as.vector()/as.matrix()/as.data.frame()/as.factor()/as.logical() #转换

#排序函数
#order 返回排序后的索引
mtcars[order(mtcars$mpg,-mtcars$cyl),]
#sort 直接排序,返回排序后结果
sort(mtcars$mpg,decreasing = T)
#rank 返回排名(相同排名会出现小数)
rank(mtcars$mpg)

#合并函数
merge(df1,df2,by=c("ID","Country"))
cbind(df1,df2,df3) #必须相同行数,以同顺序排序
rbind(df1,df2)
dplyr::left_join(df1,df2,by="ID") #right_join/full_join

mtcars[,c(2:4)] #选列
mtcars[,c(-2,-5)] #剔除列
mtcars$hp <- mtcars$wt <- NULL #剔除两列,NULL未定义(不同于NA)
mtcars[!(names(mtcars) %in% c("hp","wt"))] #是否包含所选列名

mtcars[1:3,] #选行
mtcars[mtcars$mpg>20 & mtcars$vs=="0",]

#取子集
subset(mtcars,mpg>20 | hp<90,select = mpg:hp) #选行又选列

#随机抽样
mtcars[sample(1:nrow(mtcars),3,replace=F),]

--------------第5章:高级数据管理--------------

#1.数学函数
abs(-1)
sqrt(25)
ceiling(3.2) #不小于某值的最小整数
floor(3.2) #不大于某值的最大整数
trunc(3.2) #截取整数
round(3.456,digits = 2) #保留2位小数(四舍五入)
signif(3.456,digits=2) #保留2位有效数字(四舍五入)
cos(x)/sin(x)/tan(x)
acos(x)/asin(x)/atan(x)
log(4,base = 2)
log(10) #取自然对数,而非ln(4)
log10(10) #常用对数
exp(2) #指数,即e^2

#总结R语言中取整运算主要包括以下五种:floor()向下取整,ceiling()向上取整,round()四舍五入取整,turnc()向0取整,signif()保留给定位数的精度
#以上函数可直接用在数值向量、矩阵或数据框中

#2.统计函数
x <- c(1,1.2,4,3,6,9,3,23,0.001,10)
mean(x)
mean(x,trim = 0.05,na.rm = T) #去掉最大和最小的5%数据以及缺失值后的均值
median(x)
sd(x) #标准差
var(x)
mad(x) #绝对中位差:统计离差,是一种鲁棒统计量,MAD=median(∣Xi-median(X)∣)
quantile(x) #求分位数
quantile(x,1/4) #25%分位数
quantile(x,0.9) #90%分位数
range(x) #值范围
sum(x)
diff(x) #滞后差分,默认滞后1位,即后一位数减前一位数
diff(x,lag = 2)
min(x)
max(x)
scale(x) #按列进行中心化或标准化
scale(x,center = T,scale = T) #默认。center中心化,center和scale标准化
scale(dataframe) #同样对矩阵或数据框的列进行均值为0,标准差位1的标准化,相当于Z score
scale(dataframe)*sd+m #进行任意均值m和标准差sd的归一化
transform(dataframe,var=scale(var)) #仅对矩阵/数据框的指定列进行归一化

#3.概率函数
#d=密度函数density
#p=分布函数
#q=分位数函数quantile
#r=随机数生成函数random

#eg:正态分布norm
dnorm(x) 
pnorm(1.96) #曲线下方面积
qnorm(0.9,mean = 100,sd=200) #0.9分位点值
rnorm(50,mean = 50,sd=10) #生成50个正态随机数

a <- pretty(c(-5,5),30) #pretty(x, n)创建美观的分割点,将一个连续型变量x分割为n个区间,绘图中常用。
b <- dnorm(a)
plot(a,b,type = "l")

#其他概率分布:
beta/binom/chisq/exp/f/gamma/geom/hyper/logis/multinom/nbinom/pois/signrank/t/unif/weibull/wilcox.......

runif(5) #生成(0,1]上服从均匀分布的伪随机数
runif(5) #随机数每次都不同

set.seed(123) #设定种子,使下次结果重现。数字可随意设定,复现时指定相同即可。
runif(5)
set.seed(123)
runif(5) #复现结果,需与set.seed连用

#4.字符处理函数
x <- "adb234FGdef"
nchar(x) #字符长度,length(x)是元素的个数
length(x)

substr(x,2,4) #提取子串
grep("FG",x) #返回匹配下标
sub("FG","yx",x)
sub("\\s",".","hello world") #R语言转义\\
sub("\\.","_","hello.world") #"."需要中括起来或加转义\\,不然默认为一个字符
grepl()
gsub()

strsplit(x,"")
unlist(strsplit(x,"234"))[2]
sapply(strsplit(x,"234"), "[",2) # "["表提取某个对象一部分,即提取第2个元素

paste(x,1:3,sep = "_")
paste0(x,1:3)

toupper(x) #大写转换
tolower(x) #小写转换

#其他函数
seq(1,10,2)
rep(1:7,3)
cut(c(1:20),breaks=4) #将连续变量切割n个区间(水平因子)
table(cut(c(1:20),breaks=4,labels = c("a","b","c","d")))
pretty(c(1:20),4) #创建美观分割点(n个),常用绘图

apply(mtcars, 2, sum)
mydata <- matrix(rnorm(30),nrow = 6)
apply(mydata, 1, mean)
apply(mydata, 2, mean, trim=0.2) #可直接加函数参数
fix(mydata) #加个NA试试
apply(mydata, 2, mean, na.rm=T)

lapply() #返回列表
sapply() #返回向量

#按条件创建新变量
mtcars$new[mtcars$mpg >20 & mtcars$vs=="0"] <- "yes"
mtcars$new[mtcars$mpg <=20 & mtcars$vs=="1"] <- "no"
head(mtcars)

#控制流
#基本概念:语句{statement},条件cond(T or F),表达式expr,序列seq
#1.循环
for(i in 1:10) print("hello")
i=10;while (i>0) {print("hello");i=i-1} #确保while中条件可变

#2.条件
#if-else结构
grade <- "10"
if(!is.factor(grade)) grade <- as.factor(grade) else print("grade already is factor")

#ifelse结构(紧凑)
ifelse(as.numeric(grade)>9,"passed","failed")

#switch结构 (选择)
for (i in c("sad","happy"))
  print(
    switch(i,
      happy="yes",
      sad="no",
      angry="nono"
    )
  )

#3.自编函数
#描述统计量计算函数
mystats <- function(x,parametric=T,print=F){
  if(parametric){
    center <- mean(x);spread <- sd(x)  #参数统计量
  }else{
    center <- median(x);spread <- mad(x) #非参统计量
  }
  if(print & parametric){
    cat("mean=",center,"\n","sd=",spread,"\n")
  }else if(print & !parametric){
    cat("median=",center,"\n","mad=",spread,"\n")
  }
  result <- list(center=center,spread=spread)
  return(result)
}

##验证以上函数
set.seed(123)
x <- rnorm(100)
mystats(x)
mystats(x,parametric = F)
mystats(x,parametric = F,print = T)
mystats(x,parametric = T,print = T)


#switch自编函数
mydate <- function(type="long"){
  switch(type,
         long=format(Sys.time(),"%A %B %d %Y"),
         short=format(Sys.time(), "%m-%d-%y"),
         cat(type, "is note a recognized type\n") 
         #cat捕获用户输入错误,也可用warning(提示错误),message(诊断信息),stop(停止执行)等函数
         )
}

##验证以上函数
mydate()
mydate("long") #默认
mydate("short")
mydate("x")


#整合(aggregate)和重塑(reshape)
t(mtcars)
head(mtcars)
aggregate(mtcars, by=list(mtcars$cyl,mtcars$gear), FUN = mean, na.rm=T)

library(reshape2)
md <- melt(mtcars,id=c("mpg","cyl")) #融合,宽数据变长数据
#提取id列,其他列全部融合
md2 <- dcast(md,mpg+cyl~variable) #重塑,长数据变宽数据
head(md2)
dcast(md,mpg+variable~cyl)
dcast(md,cyl+variable~mpg)
#使用mpg对cyl和variable分组
#公式的左边每个变量都会作为结果中的一列,而右边的变量被当成因子类型,每个水平都会在结果中产生一列。

dcast(md,mpg~variable,mean)
dcast(md,cyl~variable,mean)
dcast(md,mpg~cyl,mean)

#dcast-输出时返回一个数据框。acast-输出时返回一个向量/矩阵/数组

转载于:https://www.cnblogs.com/jessepeng/p/10604371.html

With more than 200 practical recipes, this book helps you perform data analysis with R quickly and efficiently. The R language provides everything you need to do statistical work, but its structure can be difficult to master. This collection of concise, task-oriented recipes makes you productive with R immediately, with solutions ranging from basic tasks to input and output, general statistics, graphics, and linear regression. Each recipe addresses a specific problem, with a discussion that explains the solution and offers insight into how it works. If you're a beginner, R Cookbook will help get you started. If you're an experienced data programmer, it will jog your memory and expand your horizons. You'll get the job done faster and learn more about R in the process. * Create vectors, handle variables, and perform other basic functions * Input and output data * Tackle data structures such as matrices, lists, factors, and data frames * Work with probability, probability distributions, and random variables * Calculate statistics and confidence intervals, and perform statistical tests * Create a variety of graphic displays * Build statistical models with linear regressions and analysis of variance (ANOVA) * Explore advanced statistical techniques, such as finding clusters in your data "Wonderfully readable, R Cookbook serves not only as a solutions manual of sorts, but as a truly enjoyable way to explore the R language-one practical example at a time." -Jeffrey Ryan, software consultant and R package author
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值