一、tidyverse的简介
- tidyr
- dplyr
- stringr
- ggplot2
二、管道符号%>%
merge通常取交集
练习7.1
stringr的用法
rm(list = ls())
if(!require(stringr))install.packages('stringr')
library(stringr)
x <- "The birch canoe slid on the smooth planks."
x
###1.检测字符串长度
length(x) #长度为1的向量,只有一个元素
str_length(x) #有多少个字符
###2.字符串拆分与组合
str_split(x," ") #以空格为分隔符,产生列表(两个中括号,注意下方的数据结构)
> class(str_split(x," "))
[1] "list"
> class(str_split(x," ")[[1]])
[1] "character"
#把拆分的字符串合并
x2 = str_split(x," ")[[1]]
x2
[1] "The" "birch" "canoe" "slid"
[5] "on" "the" "smooth" "planks."
> str_c(x2,collapse = " ")
[1] "The birch canoe slid on the smooth planks."
> str_c(x2,1234,sep = "+")
[1] "The+1234" "birch+1234"
[3] "canoe+1234" "slid+1234"
[5] "on+1234" "the+1234"
[7] "smooth+1234" "planks.+1234"
###3.提取字符串的一部分
str_sub(x,5,9) #提取X这个字符的第五位到第九位,空格算进去
[1] "birch"
###4.大小写转换
> str_to_upper(x2)
[1] "THE" "BIRCH" "CANOE" "SLID"
[5] "ON" "THE" "SMOOTH" "PLANKS."
> str_to_lower(x2)
[1] "the" "birch" "canoe" "slid"
[5] "on" "the" "smooth" "planks."
> str_to_title(x2)
[1] "The" "Birch" "Canoe" "Slid"
[5] "On" "The" "Smooth" "Planks."
###5.首字母字符串排序
> str_sort(x2)
[1] "birch" "canoe" "on" "planks."
[5] "slid" "smooth" "the" "The"
###6.字符检测(重点)
> str_detect(x2,"h") #对X2向量的每个元素进行检查是否有h,有=T
[1] TRUE TRUE FALSE FALSE FALSE TRUE TRUE
[8] FALSE
#可以用来给向量取子集
> x2[str_detect(x2,"h")] #挑选出x2向量里含有h这个字符的元素
[1] "The" "birch" "the" "smooth"
> str_starts(x2,"T") #是否以T为开头
[1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE
[8] FALSE
> str_ends(x2,"e")
[1] TRUE FALSE TRUE FALSE FALSE TRUE FALSE
[8] FALSE
> str_detect(x2,"th")
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE
[8] FALSE
###与sum和mean连用,可以统计匹配的个数和比例
> c(28738,T,F) #T=1, F=0
[1] 28738 1 0
> sum(str_detect(x2,"th")) #逻辑值和SUM连用:统计TRUE的个数
[1] 2
> mean(str_detect(x2,"th"))#TRUE占总体百分之多少
[1] 0.25
###7.提取匹配到的字符串
> str_subset(x2,"h")
[1] "The" "birch" "the" "smooth"
等同于
> x2[str_detect(x2,"h")]
###8.字符计数
> str_count(x," ")
[1] 7
> str_count(x2,"o")
[1] 0 0 1 0 1 0 2 0
###9.字符串替换
> str_replace(x2,"o","A") #默认只替换出现的第一个o
[1] "The" "birch" "canAe" "slid"
[5] "An" "the" "smAoth" "planks."
> str_replace_all(x2,"o","A")
[1] "The" "birch" "canAe" "slid"
[5] "An" "the" "smAAth" "planks."
###结合正则表达式更加强大
#练习6-2
#Bioinformatics is a new subject of genetic data collection,analysis and dissemination to the research community.
#1.将上面这句话作为一个长字符串,赋值给tmp
#2.拆分为一个由单词组成的向量,赋值给tmp2(注意标点符号)
#3.用函数返回这句话中有多少个单词。
#4.用函数返回这句话中每个单词由多少个字母组成。
#5.统计tmp2有多少个单词中含有字母"e"