pangxie的个人博客分享 http://blog.sciencenet.cn/u/pangxie

博文

对tidyverse学习

已有 1484 次阅读 2021-3-9 20:47 |个人分类:科研笔记|系统分类:科研笔记

参考来自https://www.jianshu.com/p/a081a791ae03

#install.packages("tidyverse")
library(tidyverse)
View(iris)  #可以像excel一样查看数据
#Sepal.Length(花萼长度),Sepal.Width(花萼宽度)
#Petal.Length(花瓣长度),Petal.Width(花瓣宽度)
#Species(花的类型),其中花有3种类型(setosa、versicolor、virginica)
attributes(iris) #查看数据属性
#3.使用dplyr对数据进行操作
#3.1 select(按名称选取列)
select(iris,Sepal.Length,Petal.Length,Species)
#为了查看方便也可以只查看前6行
head(select(iris,Sepal.Length,Petal.Length,Species))
#将筛选出来的结果通过赋值操作符<-给一个变量,如下所示
#基础的可视化,按照分组Species进行画散点图
p <- select(iris,Sepal.Length,Petal.Length,Species)
ggplot(p,aes(Sepal.Length,Petal.Length))+
  geom_point(aes(color=Species),size=2)
#select选择2列之间的所有列
select(iris,(Sepal.Length:Petal.Length))
#select选择不在2列之间的所有列
select(iris,-(Sepal.Length:Petal.Length))
##select()与everythin()函数结合使用可以改变列的顺序
p1<-select(iris,Species,Petal.Width,Sepal.Width,
       Sepal.Length,Petal.Length,everything())
#3.2 filter(按值筛选行)
p2<-filter(iris,Sepal.Length >=5,Petal.Length >=2)
#对筛选数据进行画图成现
p3 <- filter(iris,Sepal.Length >=5,Petal.Length >=2)
ggplot(p3,aes(Sepal.Length,Petal.Length))+
  geom_point(aes(color=Species),size=2)
#R中的比较运算符:>、>=、<、<=、!=(不等于)、==(等于)
#R中的逻辑运算符:&表示"与”,|表示“或”,!表示“非”
#3.3 arrange(改变行顺序)
#根据Petal.Width列的数据进行排序,默认为升序
arrange(iris,Petal.Width)
#desc()可以按列进行降序排序:
arrange(iris,desc(Petal.Width))
#3.4 rename(更改列名称)
#新名称在前,原始名称在后
p4<-rename(iris,length=Sepal.Length)
#3.5 mutate(添加新列)
p5<-mutate(iris,group ="A",Length=10)
summarize(iris,mean(Sepal.Length),
          sd(Sepal.Length))          
p6<-iris %>% group_by(Species) %>% 
  summarize(m = mean(Sepal.Length,na.rm=T))
# na.rm=T 表示移除缺失数据
#利用管道可以简化代码,提高代码阅读流畅性:
p7 <- filter(iris,Sepal.Length >=5,Petal.Length >=2)
p8 <- group_by(p1,Species)
p9 <- filter(p2,Species=="virginica")
ggplot(p3,aes(Sepal.Length,Petal.Length))+
  geom_point(aes(color=Species),size=2)

p10<-iris %>% filter(Sepal.Length >=5,Petal.Length >=2) %>%
  group_by(Species) %>% filter(Species=="virginica") %>%
  ggplot(aes(Sepal.Length,Petal.Length))+
  geom_point(aes(color=Species),size=2)
#上述与p10这2段代码结果相同,可以明显看到使用了%>%减少了中间变量,
#提高了代码的可阅读性
#管道的原理就是将%>%左边的变量传递到右边的.处,通常在正式书写时可省略.
iris %>% filter(.,Sepal.Length >=5,Petal.Length >=2)
#3.6 count() 计算每组值的次数
iris %>% count(Species)




https://blog.sciencenet.cn/blog-3448646-1275830.html

上一篇:差异分析检验流程
下一篇:迁移R包
收藏 IP: 122.194.1.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-7-12 05:30

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部