在学习数据科学中的R语言[1]时,所做的记录,对一些内容加了注释,方便查阅。
需要载入的R包
一开始,在载入tidyverse时,发现dplyr等包的版本太低报错,在Rstudio的界面上找到packages点开,搜索,版本太低的包,卸载,然后重新安装即可,也可以用代码卸载:'remove.packages("包名")'
library(tidyverse)
# install.packages("dplyr")
library(patchwork)#如果没安装,就用install.packages()安装后再载入
所用的数据集
df <- tibble(
name=c("Alice","Alice","Bob","Bob","Carol","Carol"),
type=c("english","math","english","math","english","math"),
score=c(60.2,95.7,98.7,89.4,76.8,92.3)
)
df
add_count()
想增加一列,代表每人参加的考试次数
df %>%
group_by(name) %>%
mutate(n=n()) %>% #增加一列通常用的方法
ungroup()
一行代码能够实现
df %>%
add_count(name)#增加一列表示每个人出现的1次数
nth()、first()、last()
nth()表示选择向量或数据框的第n个变量,first表示选择第一个,last表示最后一个,括号里是向量或者数据框
test <- c("w","g","w","a","m","s")
test %>% nth(4)
test %>% first()
test %>% last()
列变量重新排序
当变量众多时,想把score放在第一列
df %>%
select(score,everything())
if_else()
df %>%
assess=if_else(score>85,"wonderful","great")
case_when()
df %>%
assess=case_when(
score<70~"general",
score>=70&score<80~"good",
score>=80&score<90~"very good",
score>90~"wonderful"
)
找出成绩排在前几名的学生
df %>%
top_n(3,score)
取反操作
很多时候我们会判断某个数据在不在某个向量或者数据框中,也需要一个判断不属于的字符
2:7%in%c(1:6)#属于符号的应用
'%nin%' <- Negate('%in%')#定义不属于符号,就是属于取反
2:7%nin%c(1:6)
drop_na()
删除存在缺失值的行,括号里面时需要处理的数据框
replace_na()
将数据框中存在的缺失值进行替换
df %>%
mutate(score=replace_na(score,0))#将score中存在的缺失值替换为0并将新的score替换
df %>%
mutate(score=replace_na(score,mean(score,na.rm=TRUE)))#na.rm=TRUE表示,mean的结果是去除缺失值计算后的值,也就是不考虑缺失值的存在
summarise()
library(gapminder)
gapminder %>%
group_by(continent) %>% #将数据按continent分组
summarise(
avg_gdpPercap=mean(gdpPercap)
)
summarise()也可以生成一个list
library(gapminder)
gapminder %>%
group_by(continent) %>%
summarise(test=list(t.test(gdpPercap))) %>%
mutate(tidied=purrr::map(test,broom::tidy)) %>% #map()表示一次应用一元函数到一个序列的每个元素上,broom::tidy表示模型的参数信息,broom::glance表示模型的评估信息
unnest(tidied) %>%
ggplot(aes(estimate,continent))+
geom_point()+
geom_errorbarh(aes(
xmin=conf.low,
xmax=conf.high
))
#BiocManager::install("")
线性回归
gapminder %>%
group_by(continent) %>%
summarise(test=list(lm(lifeExp~gdpPercap))) %>%
mutate(tidied=purrr::map(test,broom::tidy,conf.int=TRUE)) %>%
unnest(tidied) %>%
filter(term!="(Intercept)") %>%
ggplot(aes(estimate,continent))+
geom_point()+
geom_errorbarh(aes(
xmin=conf.low,
xmax=conf.high,
height=.3
))
count()+fct_reorder()+geom_col()+coord_flip()
gapminder %>%
distinct(continent,country) %>% #distinct用来去除重复值,里面还有一个参数如果keep_all=TRUE表示保留输出框中的所有其它变量
count(continent) %>% #计算continent的频数
mutate(coll=if_else(continent=="Asia","red","gray")) %>% #增加一列变量coll表示颜色
ggplot(aes(x=fct_reorder(continent,n),y=n))+#fct_recoder表示将continent因子水平根据n的中位数进行重排序,默认是升序排序(desc=FALSE)
geom_text(aes(label=n),hjust=-0.2)+#geom_text表示将文本直接添加到绘图中,里面参数size用来修改字体大小,label表示标记的文字,hjust控制水平对齐,负号表示在图形之外,vjust控制垂直对齐
geom_col(width=0.8,aes(fill=coll))+#geom_col表示柱状图
coord_flip()+#表示将x轴和y轴进行对换
theme_classic()+#经典主题:无网格线,有轴线风格的主题
theme(panel.grid=element_blank(),panel.background = element_rect(color="black",size=0))+#对主题进行修改,加上边框
scale_fill_manual(values=c("#b3b3b3a0","#D55E00"))+#设置填充颜色
theme(legend.position="none",#不设图例
axis.text=element_text(size=11))+#坐标轴的字体大小设为11号
labs(title="My title",x="")#设置标题名字和x轴的名字
gapminder %>%
distinct(continent,country) %>%
count(continent) %>%
ggplot(aes(x=fct_reorder(continent,n),y=n))+
geom_text(aes(label=n),hjust=-0.2)+
geom_col(width=0.8,aes(fill=continent=="Asia"))+
coord_flip()+
theme_classic()+
theme(panel.grid=element_blank(),panel.background=element_rect(color="black",size=0))+
scale_fill_manual(values=c("#b3b3b3a0","#D55E00"))+
annotate("text",x=3.8,y=48,label="this is special",color="#D55E00",size=5)+#annotate表示添加自定义文本,线段等,先定义添加的文本“text"然后写明位置和内容
annotate(geom="curve",x=4.1,y=48,xend=4.1,yend=35,curvature=1,arrow=arrow(length=unit(2,"mm")))+#添加内容为曲线,(x,y)表示起点,(xend,yend)表示终点,arrow表示箭头的长度,curvature表示弯曲的程度
theme(legend.position="none",
axis.text=element_text(size=11))+
labs(title="My title",x="")
参考资料
[1]数据科学中的R语言: https://bookdown.org/wangminjie/R4DS/tidyverse-tips.html