在数据处理过程中我们常常需要对数据类型进行转换,那让我们来看看有没有更加简便的方法
测试数据ToothGrowth
ToothGrowth描述了维生素C对豚鼠牙齿生长的影响
ToothGrowth %>% as_tibble()
# A tibble: 60 x 3
len supp dose
<dbl> <fct> <dbl>
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10 VC 0.5
我们可以看到len(牙齿长度)与dose(剂量)的数据类型为del
双精度浮点数,supp为因子
问题:把dose
数据类型改为fct
传统方法
df <- ToothGrowth %>% as_tibble()
df$dose <- as.factor(df$dose)
df
# A tibble: 60 x 3
len supp dose
<dbl> <fct> <fct>
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10 VC 0.5
可以看到虽然目的达到了但是处理过程很不优雅,现在我们已经学习了tidyverse
的一些基本函数,同时也熟悉了使用%>%
进行参数的传递,那么数据类型转换有没有优雅的写法哪,当然有请继续往下看
dplyr进行数据类型转换
ToothGrowth %>% as_tibble() %>%
mutate(dose = as.factor(dose))
# A tibble: 60 x 3
len supp dose
<dbl> <fct> <fct>
1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10 VC 0.5
可以看到比较优雅的完成了格式转换,那么如果我们有多组数据要进行格式转换怎么办
指定数据内容对其进行了类型转换
iris %>% as_tibble() %>%
mutate_at(vars(Sepal.Length,Petal.Width),funs(as.character))
对整个数据类型进行转换
iris %>% as_tibble() %>% mutate_if(is.double,as.character)
iris %>% as_tibble() %>% mutate(across(where(is.double),as.character))
注:across
函数的作用非常强大请参考tidyverse官网认真学习
经上面的介绍我们以一种比较优雅的方法完成了数据类型的转换,那么还有没有更加简单的方法那,当然有!!!!!
convert 您的数据类型
# convert 必须与数据类型转换功能一起使用:
* chr 转换为字符
* num 转换为数字
* int 转换为整数
* lgl 转换为逻辑
* fct 转换为因子
* dte 转换为日期
* dtm 转换为日期时间
安装hablar
install.packages("hablar")
library(hablar)
ToothGrowth %>% as_tibble() %>%
convert(fct(dose)
iris %>% as_tibble() %>%
convert(chr(Sepal.Length,Petal.Width))
iris %>% as_tibble() %>%
convert(fct(contains("h")))
可以看到代码更加的简洁优雅,配合上tidyverse
可以大大提高代码阅读性
网友评论