生信菜鸟团
如有问题或建议,请公众号留言
Stringr
本章将向您介绍r中的字符串操作,您将了解字符串如何工作以及如何手工创建它们,但是本章的重点将放在正则表达式,或简称regexp上。正则表达式非常有用,因为字符串通常包含非结构化或半结构化数据,regexp是一种用于描述字符串中的模式的简明语言。当你第一次看到regexp时,你会以为是一只猫在你的键盘上走过,但是随着你理解的提高,它们很快就会变得有意义。
library(tidyverse)
library(stringr)
stringr常用几大函数
求字符长度: str_length() 相当于length()
字符合并: str_c() 相当于paste()
字符截取: str_sub()相当于substring()
正则表达式: str_view()
计算字符串长度
str_length(c('a', 'R for data science', NA))
#> [1] 1 18 NA
合并字符串
str_c('x', 'y')
#> [1] 'xy'
str_c('x', 'y', 'z')
#> [1] 'xyz'
str_c('x', 'y', sep = ', ')
#> [1] 'x, y'
str_c(c('x', 'y', 'z'), collapse = ', ')
[1] 'x, y, z'
> str_c(c('x', 'y', 'z'), sep = ', ')
[1] 'x' 'y' 'z'
> str_c(c('x', 'y'), sep = ', ')
[1] 'x' 'y'
> str_c('x', 'y', sep = ', ')
[1] 'x, y'
强调一点,请仔细体会str_c()中的sep和collapse参数的不同点,就是collapse代表的合并为一个引号下的字符串,而sep则是分开为多个字符串
字符串截取
相当于substring
x <>'Apple', 'Banana', 'Pear')
str_sub(x, 1, 3)
#> [1] 'App' 'Ban' 'Pea'
# negative numbers count backwards from end
str_sub(x, -3, -1)
#> [1] 'ple' 'ana' 'ear'
str_sub('a', 1, 5)
#> [1] 'a'
str_sub('a', 1, 5)
#> [1] 'a'
上面的代码就是告诉我们sub_str()第一个参数为截取对象,第二、三个参数为要截取的起点和终点,当然是从1开始,如果截取的数字前面加上负号代表的就是倒叙截取
同时str_sub还可以用来赋值比如
正则表达式 str_view函数
R里面的正则
. 代表一个任意字符
\. 代表点号自己
\d 代表任意数字
\s 代表空格
[abc] 代表a/b/c
[\^abc] 代表非a,非b,非c
^匹配字符串的开始。
$以匹配字符串的末尾
? 代表0次或一次
+ >=1 次
* >=0 次
x <>'apple', 'banana', 'pear')
str_view(x, 'an')
apple
banana
pear
x <>'apple', 'banana', 'pear')
str_view(x, '.a.')
apple
banana
pear
str_view(fruit, '(..)\\1', match = TRUE)
banana
coconut
cucumber
jujube
papaya
salal berry
加括号,以及数字代表什么呢?加括号就是代表你的对象被选中,后续匹配的还是你的数字,相当于叠字
就像上面的anan,coco等
下周继续!