生信星球培训第三十七期

学习小组DAY6——学习R包

2020-02-19  本文已影响0人  生信小工厂
DAY6

学习R包

一、安装和加载R包

step1:镜像设置
通过命令options()$repos检验RStudio的镜像,如果回到了R的国外官网我们需要运行如下代码

# options函数就是设置R运行过程中的一些选项设置
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #对应清华源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #对应中科大源
# 当然可以换成其他地区的镜像

设置成功后如果再次打开RStudio用命令options()$BioC_mirror如果是国内镜像则成功,如果是国外官网则需要进行以下步骤。
首先用file.edit('~/.Rprofile')来编辑文件,再在文件中输入

options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) 
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") 

然后在用命令options()$reposoptions()$BioC_mirror来检验就可以看到镜像是国内的路径了。
step2:安装
安装R包的命令是

install.packages("包")
#或者
BiocManager::install("包")

这两个命令的选择取决于安装的包存在于CRAN网站还是Biocductor

step3:加载
下面两个命令都可以加载

library(包)
require(包)

以dplyr包为例,四行命令安装加载dplyr包

options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) 
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") 
install.packages("dplyr")
library(dplyr)

示例数据使用内置数据iris的简化版:

test <- iris[c(1:2,51:52,101:102),]
iris简化版数据

Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理。Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集。数据集包含150个数据样本,分为3类,每类50个数据,每个数据包含4个属性。可通过花萼长度(Sepal.Length),花萼宽度(Sepal.Width),花瓣长度(Petal.Length),花瓣宽度(Petal.Width)4个属性预测鸢尾花卉属于(Setosa,Versicolour,Virginica)三个种类中的哪一类。(百度百科)

二、dplyr五个基础函数

(1)按列号筛选

例:输入命令select(test,4) #选取第四列

筛选列
例:输入命令select(test,c(2,5)) #选取第2列和第5列
筛选列
(2)按列名筛选

例:输入命令select(test,Sepal.Length) #选取名为Sepal.Length的那一列

筛选列
例:输入命令select(test, Petal.Length, Petal.Width) #选取名为Petal.Length和Petal.Width这两列
筛选列
例:输入命令
vars <- c("Petal.Length", "Petal.Width")
select(test, one_of(vars))  #选取名为Petal.Length和Petal.Width这两列
筛选列

三、dplyr两个实用技能

test %>% 
  group_by(Species) %>% 
  summarise(mean(Sepal.Length), sd(Sepal.Length))
管道操作

四、dplyr处理关系数据(即将两个表进行连接)

首先引入两个表格test1,test2
输入命令

options(stringsAsFactors = F)

test1 <- data.frame(x = c('b','e','f','x'), 
                    z = c("A","B","C",'D'),
                    stringsAsFactors = F)
test1
test1
test2 <- data.frame(x = c('a','b','c','d','e','f'), 
                    y = c(1,2,3,4,5,6),
                    stringsAsFactors = F)
test2 
test2
上一篇 下一篇

猜你喜欢

热点阅读