R语言学习之数据的清理和转化

来源:互联网 发布:嵌入式linux开发流程 编辑:程序博客网 时间:2024/05/16 03:16

处理字符串

grep grepl 和regexpr函数都能找到与模式相匹配的字符串 sub 和 gsub函数能替换匹配的字符串

加载strngr包,fixed里面为要匹配的字符串 返回匹配的字符串序列

> library(stringr)> multiple <- str_detect(english_monarchs$domain,fixed(","))> english_monarchs[multiple,c("name","domain")]                                        name                    domain17                                      Offa       East Anglia, Mercia18                                      Offa East Anglia, Kent, Mercia19                         Offa and Ecgfrith East Anglia, Kent, Mercia20                                  Ecgfrith East Anglia, Kent, Mercia22                            C<U+009C>nwulf East Anglia, Kent, Mercia23               C<U+009C>nwulf and Cynehelm East Anglia, Kent, Mercia24                            C<U+009C>nwulf East Anglia, Kent, Mercia25                                  Ceolwulf East Anglia, Kent, Mercia26                                 Beornwulf       East Anglia, Mercia82             Ecgbehrt and <U+00C6>thelwulf              Kent, Wessex83             Ecgbehrt and <U+00C6>thelwulf      Kent, Mercia, Wessex84             Ecgbehrt and <U+00C6>thelwulf              Kent, Wessex85    <U+00C6>thelwulf and <U+00C6>eelstan I              Kent, Wessex86                          <U+00C6>thelwulf              Kent, Wessex87 <U+00C6>thelwulf and <U+00C6>eelberht III              Kent, Wessex88                      <U+00C6>eelberht III              Kent, Wessex89                         <U+00C6>thelred I              Kent, Wessex95                                     Oswiu       Mercia, Northumbria

使用正则表达式来匹配多个要匹配的字符串,这是来匹配逗号和and

> ruler <- str_detect(english_monarchs$name,",|and")> english_monarchs[ruler & !is.na(ruler)]
把name一列拆分掉,则可以使用str_splist函数

> indival <- str_split(english_monarchs$name,",|and")> head(indival[sapply(indival,length)>1])[[1]][1] "Sigeberht " " Ecgric"   [[2]][1] "Hun"      " Beonna " " Alberht"[[3]][1] "Offa "     " Ecgfrith"[[4]][1] "C\u009cnwulf " " Cynehelm"    [[5]][1] "Sighere " " Sebbi"  [[6]][1] "Sigeheard " " Swaefred" 

st_count是用来统计有多少个字符串

> str_count(english_monarchs$name,th)

str_replace函数来代替字符串中的某一个

ignore.case来忽略某一个字符或字符串


0 0
原创粉丝点击