R语言学习:字符串替换、tidy系列包、Bland-Altman图、RODBC包、UMAP降维
专题介绍:R是一种广泛用于数据分析和统计计算的强大语言,于上世纪90年代开始发展起来。得益于全世界众多 爱好者的无尽努力,大家继而开发出了一种基于R但优于R基本文本编辑器的R Studio(用户的界面体验更好)。也正是由于全世界越来越多的数据科学社区和用户对R包的慷慨贡献,让R语言在全球范围内越来越流行。其中一些R包,例如MASS,SparkR, ggplot2,使数据操作,可视化和计算功能越来越强大。R是用于统计分析、绘图的语言和操作环境。R是属于GNU系统的一个自由、免费、源代码开放的软件,它是一个用于统计计算和统计制图的优秀工具。R作为一种统计分析软件,是集统计分析与图形显示于一体的。它可以运行于UNIX、Windows和Macintosh的操作系统上,而且嵌入了一个非常方便实用的帮助系统,相比于其他统计分析软件,R的学术性开发比较早,适合生物学和医学等学术学科的科研人员使用。
2021年第35周。
这一周R语言学习,记录如下。
01
字符串替换
数据清洗的时候,会用到字符串的替换操作,以实现数据的整洁性。
stringr包
第一组:
1 str_replace函数
2 str_replace_all函数
第二组:
1 str_remove函数
2 str_remove_all函数
library(tidyverse)
# 第一组:str_replace和str_replace_all函数
# 选择采用什么内容来替换掉与模式匹配成功的字符
fruits <- c("one apple", "two pears", "three bananas")
(fruits)
str_replace(fruits, "[aeiou]", "-")
# 基于模式匹配成功后,替换掉满足要求首个字母
str_replace_all(fruits, "[aeiou]", "-")
# 基于模式匹配成功后,替换掉满足要求所有的字母
# 第二组:str_remove和str_remove_all
# 有点类似第一组,直接移除操作
library(tidyverse)
fruits <- c("one apple", "two pears", "three bananas")
(fruits)
str_remove(fruits, "[aeiou]")
str_remove_all(fruits, "[aeiou]")
02
tidy系列包
我常用的tidy开头的R包
tidyverse:包含了数据科学工作R包套件,提升了数据科学工作的效率。
tidymodels:适合于数据建模,提升建模的效率。
tidyquant:适合金融数据分析和时序数据处理。
tidytext:适合文本数据分析。
(欢迎你补充)
03
Bland-Altman图
应用场景:一个产品,20个受试者,两种测量方式
使用Bland-Altman图直观了解两组测量数据的一致性
x轴表示两组测量的平均值,y轴表示两组测量的差异
# 数据准备
data <- data.frame(A=c(6, 5, 3, 5, 6, 6, 5, 4, 7, 8, 9,
10, 11, 13, 10, 4, 15, 8, 22, 5),
B=c(5, 4, 3, 5, 5, 6, 8, 6, 4, 7, 7, 11,
13, 5, 10, 11, 14, 8, 9, 4))
head(data)
# 数据处理
data$avg <- rowMeans(data)
data$diff <- data$A - data$B
head(data)
# 置信度计算
mean_diff <- mean(data$diff)
(mean_diff)
lower <- mean_diff - 1.96*sd(data$diff)
(lower)
upper <- mean_diff + 1.96*sd(data$diff)
(upper)
# 画Bland-Altman图
library(ggplot2)
library(showtext)
font_add("my_font1", "timesbd.ttf") # my_font1赋予字体的名称,timesbd.ttf 为 Times New Roman粗体
showtext_auto() # 全局自动使用
ggplot(data, aes(x = avg, y = diff)) +
geom_point(size=2) +
geom_hline(yintercept = mean_diff, size = 1.5) +
geom_hline(yintercept = lower, color = "red", linetype="dashed", size=1.5) +
geom_hline(yintercept = upper, color = "red", linetype="dashed", size=1.5) +
ggtitle("Bland-Altman Plot") +
ylab("Difference Between Instruments") +
xlab("Average") +
theme_classic() +
theme(
axis.line.x = element_line(size = 1.5),
axis.line.y = element_line(size = 1.5),
plot.title = element_text(face = 'bold', family = "my_font1"),
axis.title = element_text(face = 'bold', size = 15, family = 'my_font1'),
axis.text = element_text(face = 'bold', size = 15, family = 'my_font1')
)
参考资料:
https://www.r-bloggers.com/2021/08/plot-differences-in-two-measurements-bland-altman-plot-in-r/
https://statisticsglobe.com/change-font-size-of-ggplot2-plot-in-r-axis-text-main-title-legend
04
快捷键
Rmd插入R代码块:
Ctrl + Alt + I
R脚本自定义函数添加注释:
Ctrl+Alt+Shift+R
05
本地化安装github包
三步骤:
1 利用git clone命令克隆一份github上的R包
2 在RStudio进入终端(Terminal)窗口,用命令
R CMD build xx 编译R文件,生成后缀名为tar.gz的压缩文件
3 安装编译好的文件
R CMD install xx.tar.gz
06
RODBC包连接数据库
实际工作,利用RODBC包连接HIVE平台,访问大数据里面表。
操作步骤:
1 配置ODBC数据源
2 加载RODBC包
3 建立ODBC数据库连接
4 编写取数的SQL语句
5 执行SQL语句,读取表数据
6 关闭连接
参考资料:
https://blog.csdn.net/zjlamp/article/details/81272718
07
PCA降维技术及应用
PCA,一种常用的数据降维技术。
PCA的算法原理,借用《深度学习》书籍的讲解。
(源自:深度学习2.12的内容)
作者们利用线性代数知识来推导和解析PCA算法的思想和原理。
利用R语言来实现PCA数据降维,并且做可视化表示。
options(warn = -1)
options(scipen = 999)
# R包
library(tidyverse)
library(tidymodels)
# 数据导入
boston_cocktails <- readr::read_csv("./raw_data/boston_cocktails.csv")
# 数据探索
boston_cocktails %>%
count(ingredient, sort = TRUE)
# 数据清洗工作
# 把数据清洗干净
# 从行或者列入手
# 通常从列入手
cocktails_parsed <- boston_cocktails %>%
mutate(
ingredient = str_to_lower(ingredient),
ingredient = str_replace_all(ingredient, "-", " "),
ingredient = str_remove(ingredient, " liqueur$"),
ingredient = str_remove(ingredient, " (if desired)$"),
ingredient = case_when(
str_detect(ingredient, "bitters") ~ "bitters",
str_detect(ingredient, "lemon") ~ "lemon juice",
str_detect(ingredient, "lime") ~ "lime juice",
str_detect(ingredient, "grapefruit") ~ "grapefruit juice",
str_detect(ingredient, "orange") ~ "orange juice",
TRUE ~ ingredient
),
measure = case_when(
str_detect(ingredient, "bitters") ~ str_replace(measure, "oz$", "dash"),
TRUE ~ measure
),
measure = str_replace(measure, " ?1/2", ".5"),
measure = str_replace(measure, " ?3/4", ".75"),
measure = str_replace(measure, " ?1/4", ".25"),
measure_number = parse_number(measure),
measure_number = if_else(str_detect(measure, "dash$"),
measure_number / 50,
measure_number
)
) %>%
add_count(ingredient) %>%
filter(n > 15) %>%
select(-n) %>%
distinct(row_id, ingredient, .keep_all = TRUE) %>%
na.omit()
cocktails_parsed
# 把数据转换成用于建模的格式
cocktails_df <- cocktails_parsed %>%
select(-ingredient_number, -row_id, -measure) %>%
pivot_wider(names_from = ingredient, values_from = measure_number, values_fill = 0) %>%
janitor::clean_names() %>%
na.omit()
cocktails_df
# 无监督学习
# 主成分分析
# PCA
library(tidymodels)
pca_rec <- recipe(~., data = cocktails_df) %>%
update_role(name, category, new_role = "id") %>%
step_normalize(all_predictors()) %>%
step_pca(all_predictors())
pca_prep <- prep(pca_rec)
pca_prep
# PCA数据可视化
tidied_pca <- tidy(pca_prep, 2)
tidied_pca %>%
filter(component %in% paste0("PC", 1:5)) %>%
mutate(component = fct_inorder(component)) %>%
ggplot(aes(value, terms, fill = terms)) +
geom_col(show.legend = FALSE) +
facet_wrap(~component, nrow = 1) +
labs(y = NULL)
library(tidytext)
# 获取每个主成分的Top8
tidied_pca %>%
filter(component %in% paste0("PC", 1:4)) %>%
group_by(component) %>%
top_n(8, abs(value)) %>%
ungroup() %>%
mutate(terms = reorder_within(terms, abs(value), component)) %>%
ggplot(aes(abs(value), terms, fill = value > 0)) +
geom_col() +
facet_wrap(~component, scales = "free_y") +
scale_y_reordered() +
labs(
x = "Absolute value of contribution",
y = NULL, fill = "Positive?"
)
# 基于主成分的可视化分析
juice(pca_prep) %>%
ggplot(aes(PC1, PC2, label = name)) +
geom_point(aes(color = category), alpha = 0.7, size = 2) +
geom_text(check_overlap = TRUE, hjust = "inward", family = "IBMPlexSans") +
labs(color = NULL) +
theme_classic()
08
UMAP数据降维技术
生物信息高维数据处理和分析,经常会用到UMAP这个算法,一种基于流形拓扑结构的数据降维技术。
承接07的内容,采用UMAP数据降维和可视化表示。
# 无监督学习UMAP算法
# 拓扑结构数据分析
# 流形学习思想
library(embed)
umap_rec <- recipe(~., data = cocktails_df) %>%
update_role(name, category, new_role = "id") %>%
step_normalize(all_predictors()) %>%
step_umap(all_predictors())
umap_prep <- prep(umap_rec)
umap_prep
# 基于UMAP的数据可视化
juice(umap_prep) %>%
ggplot(aes(umap_1, umap_2, label = name)) +
geom_point(aes(color = category), alpha = 0.7, size = 2) +
geom_text(check_overlap = TRUE, hjust = "inward", family = "IBMPlexSans") +
labs(color = NULL) +
theme_classic()
学习资料:
https://juliasilge.com/blog/cocktail-recipes-umap/
09
R做数据科学工作的常用R包
R做数据科学的常用R包
1 ggplot2包,最流行的数据可视化包
2 tidyr包,数据整洁包
3 dplyr包,数据处理和分析包
4 tidyquant包,适合金融分析的包
5 caret包,适合分类和回归问题的包
6 tidyverse包,数据科学工作套件
7 e1071包,可做SVM、朴素贝叶斯、聚类、傅里叶变换的包
8 plotly包,生成动态图的包
9 knitr包,适合做可重复性研究的包,方便生成各种格式的报告
10 mlr3包,用于做机器学习的包
11 xgboost包,实现xgboost算法的包
参考资料:
https://finnstats.com/index.php/2021/04/07/essential-packages-in-r/
10
查看R语言函数源代码
R语言是一个开源的软件和平台
研读R源代码,是一种有效提升R语言能力的好办法
查看源代码的常用方式
方式一:直接写函数名
方式二:page函数
用记事本查看
方式三:edit函数
方式四:对于计算方法不同的函数,用methods函数
方式五:对于methods得出的带星号标注的源代码,用函数getAnywhere
(说明:函数代码太长,展示了其中一部分)
方式六:直接下载源代码包,进行阅读。
自动化变量分箱的包woeBinning,在CRAN网站上面可以找到源代码包,如下图。
下载并解压,就可以查看了。
参考资料:
https://blog.csdn.net/funny75/article/details/49966275
11
预测:方法与实践
本周发现了一本优质的在线电子书《预测:方法与实践》。
阅读网址:
https://otexts.com/fppcn/
https://otexts.com/fpp2/
本书聚焦时间序列预测。
本书使用R语言,可以让你学会如何让R做预测。
R语言是免费的、开源的、跨平台的,是统计分析和预测分析的绝佳工具。
作者们在1.1节提出了一个问题:
什么是可预测的?
这个问题很有意思,我们都想做预测或者喜欢预测。
在做预测之前,我们需要想一想什么是可以预测的?什么是不可以预测的?只有这样,我们才能对症下药、有的放矢,以发挥预测的真正价值。
关于这个问题,作者们的回答。
(来源:书籍的1.1节内容)
我推荐你阅读这本书籍,阅读中有什么问题或者想法请留言,或者添加我的个人微信,大家一起讨论和学习。
12
双y轴图
利用ggplot2包绘制双y轴图,把条形图和折线图放在一起来展示。
# R 包
library(tidyverse)
library(readxl)
# 数据导入
df <- read_excel("./raw_data/fires_statistics.xlsx")
# 定制绘图函数
pic_Func <- function(data, country="Greece"){
data %>%
.[.$country==country,] %>%
ggplot(aes(x=year))+
geom_bar(aes(y=burnt_areas_ha),stat = "identity",fill="orange")+
#Bar labels(burnt_areas_ha)
geom_text(aes(y=burnt_areas_ha,label=burnt_areas_ha),vjust=-0.2,color="orange")+
#multiplied by transformation rate to tune in with the main y-axis(Burnt Areas)
geom_line(aes(y=fires_number*100),size=2,color="lightblue")+
#Line labels(fires_number)
geom_text(aes(y=fires_number,label=fires_number),vjust=1,color="lightblue")+
scale_x_continuous(breaks = seq(2009,2021,1))+
scale_y_continuous(
#for the main y-axis
labels = scales::label_number_si(),
breaks = scales::pretty_breaks(n=7),
#for the second y-axis
sec.axis = sec_axis(~./100,#divided by transformation rate, in order to be represented based on the first y-axis
name = "Number of Fires",
breaks = scales::pretty_breaks(7)),
)+
xlab("")+ylab("Burnt Areas(ha)")+
ggtitle(paste("The comparison of the volume(ha) and numbers of Forest Fires in",
country))+
theme_minimal()+
theme(
#Main y-axis
axis.title.y = element_text(color = "orange",
#puts distance with the main axis labels
margin = margin(r=0.5,unit = "cm"),
hjust = 1),#sets the main axis title top left
#Second y-axis
axis.title.y.right = element_text(color = "lightblue",
#puts distance with the second axis labels
margin = margin(l=0.5,unit = "cm"),
hjust = 0.01),#sets the second axis title bottom right
#adjusts the date labels to avoid overlap line numbers
axis.text.x = element_text(angle = 30,
vjust = 1,
hjust = 1),
panel.grid.minor = element_blank(),#removes the minor grid of panel
plot.title=element_text(face = "bold.italic",hjust = 0.5)
)
}
# 可视化
pic_Func(df, "Italy")
效果图
学习资料:
https://datageeek.com/2021/08/23/wildfires-comparison-with-ggplot2-dual-y-axis-and-forecasting-with-knn/
我创建了R语言群,添加我的微信,备注:姓名-入群,我邀请你进群,一起学习R语言。
如果你觉得文章内容有用,请关注下方公众号~
如果你想找数据工作,请关注下方公众号~
R语言资料专辑:
觉得本文不错,就顺手帮我转发到朋友圈和微信群哦,谢谢。
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!