R语言学习:Jupyter Lab构建R工作环境,处理类别型数据总结
2022年第03周。
这一周的R语言学习,记录如下。
01
Jupyter Lab构建R工作环境
如何在Jupyter Lab里配置R核,以构建R工作环境?
准备工作:
-
1 安装R软件
-
2 安装Anaconda软件
-
3 启动Anaconda的Prompt,进入到R的安装路径,启动R程序,输入如下安装命令和配置命令
install.packages(c('repr', 'IRdisplay', 'evaluate', 'crayon', 'pbdZMQ', 'devtools',
'uuid', 'digest'))
devtools::install_github('IRkernel/IRkernel')
IRkernel::installspec(user = FALSE)
-
4 退出R,启动Jupyter Lab。
q()
jupyter-lab
如下图所示:
在Jupyter Lab下,可以采用R-notebook的工作方式或者R console的工作方式。
关于在Jupyter Lab上面构建R工作环境,你有什么问题,请添加我的微信。
02
如何处理类别型数据?
在介绍处理类别型数据之前,我们先了解一下数据类型的分类,如下图所示:
1 类别型数据
类别型数据的特点:
-
1 它总是离散的
-
2 它可能分成几个组
-
3 包含名字或者标签
-
4 取值是有限的或者固定的几个值
-
5 常用于计数操作
-
6 分析时常用数据表
2 因子类型
R语言可以使用factor
类型来管理类别型数据,包括这些内容:
-
1 存储类别型数据
-
2 检查所给的数据是否是类别型
-
3 把其它数据类型转换为因子型
-
4 处理类别型数据的缺失值
-
5 指定类别型的顺序
举例说明如下
library(tidyverse)
data <- read_csv("./data/analytics_raw.csv",
col_types = cols_only(device = col_factor(levels = c("Desktop", "Tablet", "Mobile")),
gender = col_factor(levels = c("female", "male", "NA")),
user_rating = col_factor(levels = c("1", "2", "3", "4", "5"),
ordered = TRUE)))
data %>%
slice_head(n = 10)
set.seed(1234)
# 使用smaple函数做有放回地抽样
device <- sample(c("Desktop", "Mobile", "Tablet"),
size = 25,
replace = TRUE)
device
# 数据类型检验
is.factor(device)
# 数据类型转换
as.factor(device)
# 或者使用forcats包的as_factor函数
as_factor(device)
# factor函数的使用
factor(device)
factor(device, levels = c('Desktop', 'Mobile', 'Tablet'))
factor(device, levels = c('Desktop', 'Mobile'))
factor(device,
levels = c('Desktop', 'Mobile', 'Tablet'),
labels = c("Desk", "Mob", "Tab"))
set.seed(1234)
device <- sample(c("Desktop", "Mobile", "Tablet", NA), size = 25, replace = TRUE)
device
factor(device)
# 若是要把NA做一个Levels
factor(device, exclude = NULL)
rating <- sample(c("Dislike", "Neutral", "Like"),
size = 25,
replace = TRUE)
rating
is.ordered(rating)
as.ordered(rating)
factor(rating, ordered = TRUE)
# 修改排序的逻辑
factor(rating,
levels = c("Dislike", "Neutral", "Like"),
ordered = TRUE)
ordered(rating,
levels = c("Dislike", "Neutral", "Like"))
关于factor
的关键函数总结,如下图所示:
3 汇总类别型数据
类别型数据虽然不能像连续数据做极差、标准差、均值的操作,但是,它可以做如下操作:
-
1 计数和频数
-
2 比例
-
3 累积频数
-
4 交叉表
-
5 列联表
等
举例说明如下:
library(tidyverse)
library(gmodels)
library(descriptr)
# 数据导入
data <- readRDS('./data/analytics.rds')
data %>%
glimpse()
nlevels(data$device)
# Category Names
levels(data$device)
unique(data$device)
fct_unique(data$device)
# Names & Counts
table(data$device)
fct_count(data$device)
summary(data$device)
# Tables
tab <- table(data$device)
tab
prop.table(tab)
tab2 <- table(data$gender, data$device)
tab2
table(data$device, data$gender)
margin.table(tab2, 1)
margin.table(tab2, 2)
margin.table(tab2)
dimnames(tab2)
names(dimnames(tab2)) <- c("Gender", "Device")
tab2
rowSums(tab2)
colSums(tab2)
tabx <- xtabs(~gender+device, data = data)
tabx
ftable(tabx)
gen <- as.factor(as.character(data$gender))
table(gen)
table(gen, useNA = "ifany")
table(data$device, useNA = "always")
gmodels::CrossTable(data$device, data$gender)
descriptr::ds_cross_table(data, device, gender)
类别型变量,做汇总操作的关键函数,如下图所示:
4 重塑类别型数据
重塑类别型数据,可以做如下操作。
-
1 修改levels的值
-
2 添加和删除levels
-
3 修改levels的顺序
举例说明如下。
library(tidyverse)
library(car)
data <- readRDS('./data/analytics.rds')
channel <- data$channel
fct_count(channel)
fct_count(channel, sort = TRUE)
fct_count(channel, prop = TRUE)
table(fct_match(channel, "Social"))
fct_count(
fct_collapse(
channel,
Search = c("Paid Search", "Organic Search")
)
)
fct_count(
fct_recode(
channel,
Search = "Paid Search",
Search = "Organic Search"
)
)
fct_count(fct_lump_min(channel, 5000))
fct_count(
fct_other(
channel,
keep = c("Organic Search", "Direct", "Referral"))
)
fct_count(
fct_other(
channel,
drop = c("Display", "Paid Search")
)
)
fct_count(
fct_collapse(
channel,
Other = c("(Other)", "Affiliate", "Display", "Paid Search", "Social")
)
)
fct_count(
fct_recode(
channel,
Other = "(Other)",
Other = "Affiliate",
Other = "Display",
Other = "Paid Search",
Other = "Social"
)
)
fct_count(fct_anon(channel, prefix = "ch_"))
levels(fct_expand(channel, "Blog"))
levels(fct_drop(fct_expand(channel, "Blog")))
fct_count(fct_explicit_na(data$gender))
levels(channel)
levels(fct_relevel(channel, "Organic Search"))
levels(channel)
levels(fct_relevel(channel, "Referral", after = 2))
levels(channel)
levels(fct_relevel(channel, "Display", after = Inf))
levels(channel)
levels(fct_infreq(channel))
levels(channel)
levels(fct_inorder(channel))
levels(channel)
levels(fct_rev(channel))
levels(channel)
levels(fct_shuffle(channel))
5 类别型数据可视化
类别型数据可视化,可以进行如下操作。
-
1 单变量条形图
-
2 双变量条形图(分组、堆叠、成比例)
-
3 马赛克图
-
4 饼形图
-
5 甜甜圈图
5.1 条形图
library(tidyverse)
data <- readRDS('./data/analytics.rds')
# Bar Plot
ggplot(data) +
geom_bar(aes(x = device), fill = "blue") +
xlab("Device") + ylab("Count")
# Grouped Bar Plot
ggplot(data) +
geom_bar(aes(x = device, fill = gender), position = "dodge") +
xlab("Device") + ylab("Count")
# Stacked Bar Plot
ggplot(data) +
geom_bar(aes(x = device, fill = gender)) +
xlab("Device") + ylab("Count")
# Proportional Bar Plot
data %>%
select(device, gender) %>%
table() %>%
tibble::as_tibble() %>%
ggplot(aes(x = device, y = n, fill = gender)) +
geom_bar(stat = "identity", position = "fill") +
xlab("Device") + ylab("Gender")
5.2 马赛克图
# Mosaic Plot
library(ggmosaic)
ggplot(data = data) +
geom_mosaic(aes(x = product(channel, device), fill = channel)) +
xlab("Device") + ylab("Channel")
5.3 饼形图
# Pie Chart
data %>%
pull(device) %>%
table() %>%
pie()
library(plotrix)
data %>%
pull(device) %>%
table() %>%
pie3D(explode = 0.1)
data %>%
pull(device) %>%
fct_count() %>%
rename(device = f, count = n) %>%
ggplot() +
geom_bar(aes(x = "", y = count, fill = device), width = 1, stat = "identity") +
coord_polar("y", start = 0)
5.4 甜甜圈图
# Donut Chart
library(ggpubr)
data %>%
pull(device) %>%
fct_count() %>%
rename(device = f, count = n) %>%
ggdonutchart("count", label = "device", fill = "device", color = "white",
palette = c("#00AFBB", "#E7B800", "#FC4E07"))
关于类别型数据处理,你有什么问题,请添加我的微信。
我是王路情,利用R语言做数据科学工作,工作内容主要包括数据清洗与准备、数据探索、数据分析、数据挖掘、数据可视化、数据报告、建模工作环境搭建、R语言做科研论文等。我可以提供R语言和数据科学的咨询与服务。欢迎你添加我的微信,加入我创建的R语言群,一起学习和使用R语言。
如果你想学习数据科学与人工智能,请关注下方公众号~
如果你想找数据工作,请关注下方公众号~
2021年R语言学习专辑:
如果觉得本文不错,就顺手帮我转发到朋友圈和微信群哦。
请关注“恒诺新知”微信公众号,感谢“R语言“,”数据那些事儿“,”老俊俊的生信笔记“,”冷🈚️思“,“珞珈R”,“生信星球”的支持!