码迷,mamicode.com
首页 > 编程语言 > 详细

R语言学习笔记:字符串处理

时间:2014-11-02 09:14:43      阅读:436      评论:0      收藏:0      [点我收藏+]

标签:style   io   os   ar   使用   for   sp   文件   数据   

想在R语言中生成一个图形文件的文件名,前缀是fitbit,后面跟上月份,再加上".jpg",先不百度,试了试其它语言的类似语法,没一个可行的:

C#中:"fitbit" + month + ".jpg"

VB:"fitbit" & month & ".jpg"

Haskell:"fitbit" ++ month ++ ".jpg"

还想到concat之类的函数,都不行,看来只能查帮助了,原来必须要用一个paste函数。

paste()与paste0():连接字符串

paste()不仅可以连接多个字符串,还可以将对象自动转换为字符串再相连,另外它还能处理向量,所以功能更强大。

paste("fitbit", month, ".jpg", sep="")

这个函数的特殊地方在于默认的分隔符是空格,所以必须指定sep="",这样如果month=10时,就会生成fitbit10.jpg这样的字符串。

另外还有一个paste0函数,默认就是sep=""

所以paste0("fitbit", month, ".jpg")就与前面的代码简洁一点了。

要生成12个月的fitbit文件名:

paste("fitbit", 1:12, ".jpg", sep = "")

[1] "fitbit1.jpg"  "fitbit2.jpg"  "fitbit3.jpg"  "fitbit4.jpg"  "fitbit5.jpg"  "fitbit6.jpg"  "fitbit7.jpg"

[8] "fitbit8.jpg"  "fitbit9.jpg"  "fitbit10.jpg" "fitbit11.jpg" "fitbit12.jpg"

可以看出参数里面有向量时的捉对拼接的效果,如果某个向量较短,就自动补齐:

a <- c("甲","乙","丙", "丁","戊","己","庚","辛","壬","癸")

b <- c("子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥")

paste0(a, b)

[1] "甲子" "乙丑" "丙寅" "丁卯" "戊辰" "己巳" "庚午" "辛未" "壬申" "癸酉" "甲戌" "乙亥"

paste还有一个collapse参数,可以把这些字符串拼成一个长字符串,而不是放在一个向量中。

> paste("fitbit", 1:3, ".jpg", sep = "", collapse = "; ")

[1] "fitbit1.jpg; fitbit2.jpg; fitbit3.jpg"

 

nchar():求字符个数

nchar()能够获取字符串的长度,它和length()的结果是有区别的。

nchar(c("abc", "abcd"))    #求字符串中的字符个数,返回向量c(3, 4)

length(c("abc", "abcd"))  #返回2,向量中元素的个数

tolower(x) 和toupper(x) :大小写转换。

不用多说。

strsplit:字符串分割

strsplit("2014-10-30 2262 10367 7.4 18 1231 77 88 44", split=" ")

[[1]]

[1] "2014-10-30" "2262"       "10367"      "7.4"        "18"         "1231"       "77"         "88"         "44"  

实际上这个函数支持非常强大的正则表达式。

 

 

 

现在要自动生成fitbit的10月的统计图,并保存为文件fitbit_month_10.jpg。

m <- 10

jpeg(paste0("fitbit_month_", m, ".jpg"))

monthData <- fitbit[as.double(format(fitbit$date, "%m"))==m, ]

plot(format(monthData$date,"%d"), monthData$step, type="l", xlab="date", ylab="steps", main=paste("2014年",m,"月步数统计图",sep=""))

dev.off()

 

 

 

其它内容还未整理,先把网上搜到的资料放到下面。

===============================================

 

 

 

 

 

尽管R语言的主要处理对象是数字,而字符串有时候也会在数据分析中占到相当大的份量。特别是在文本数据挖掘日趋重要的背景下,在数据预处理阶段你需要熟练的操作字符串对象。当然如果你擅长其它的处理软件,比如Python,可以让它来负责前期的脏活。

 

字符串截取:substr()能对给定的字符串对象取出子集,其参数是子集所处的起始和终止位置。

字符串替代:gsub()负责搜索字符串的特定表达式,并用新的内容加以替代。sub()函数是类似的,但只替代第一个发现结果。

字符串匹配:grep()负责搜索给定字符串对象中特定表达式 ,并返回其位置索引。grepl()函数与之类似,但其后面的"l"则意味着返回的将是逻辑值。

一个例子:
我们来看一个处理邮件的例子,目的是从该文本中抽取发件人的地址。该文本在此可以下载到。邮件的全文如下所示:
----------------------------
Return-Path: skip@pobox.com
Delivery-Date: Sat Sep 7 05:46:01 2002
From: skip@pobox.com (Skip Montanaro)
Date: Fri, 6 Sep 2002 23:46:01 -0500
Subject: [Spambayes] speed
Message-ID: <15737.33929.716821.779152@12-248-11-90.client.attbi.com>

If the frequency of my laptop‘s disk chirps are any indication, I‘d say
hammie is about 3-5x faster than SpamAssassin.

Skip
----------------------------

# 用readLines函数从本地文件中读取邮件全文。
data <- readLines(‘data‘)
# 判断对象的类,确定是一个文本型向量,每行文本是向量的一个元素。
class(data)
# 从这个文本向量中找到包括有"From:"字符串的那一行
email <- data[grepl(‘From:‘,data)]
#将其按照空格进行分割,分成一个包括四个元素的字符串向量。
from <- strsplit(email,‘ ‘)
# 上面的结果是一个list格式,转成向量格式。
from <- unlist(from)
# 最后搜索包含‘@‘的元素,即为发件人邮件地址。
from <- from[grepl(‘@‘,from)]

在字符串的复杂操作中通常会包括正则表达式(Regular Expressions),关于这方面内容可以参考?regex

 

 

 

 

 

#字符串截取:
substr(x, start, stop)
substring(text, first, last = 1000000)
substr(x, start, stop) <- value
substring(text, first, last = 1000000) <- value

#字符串替换及大小写转换:
chartr(old, new, x)
casefold(x, upper = FALSE)
#匹配相关的函数:
字符完全匹配
grep()
字符不完全匹配
agrep()
字符替换
gsub()
#以上这些函数均可以通过perl=TRUE来使用正则表达式。
     grep(pattern, x, ignore.case = FALSE, extended = TRUE,
          perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE)

     sub(pattern, replacement, x,
         ignore.case = FALSE, extended = TRUE, perl = FALSE,
         fixed = FALSE, useBytes = FALSE)

     gsub(pattern, replacement, x,
          ignore.case = FALSE, extended = TRUE, perl = FALSE,
          fixed = FALSE, useBytes = FALSE)

     regexpr(pattern, text, ignore.case = FALSE, extended = TRUE,
             perl = FALSE, fixed = FALSE, useBytes = FALSE)

     gregexpr(pattern, text, ignore.case = FALSE, extended = TRUE,
              perl = FALSE, fixed = FALSE, useBytes = FALSE)
See Also:

     regular expression (aka ‘regexp‘) for the details of the pattern
     specification.

     ‘glob2rx‘ to turn wildcard matches into regular expressions.

     ‘agrep‘ for approximate matching.

     ‘tolower‘, ‘toupper‘ and ‘chartr‘ for character translations.
     ‘charmatch‘, ‘pmatch‘, ‘match‘. ‘apropos‘ uses regexps and has
     nice examples.

 

 

 

 

 

5 字符串查询:
5.1 grep和grepl函数:
这两个函数返回向量水平的匹配结果,不涉及匹配字符串的详细位置信息。

grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes =FALSE, invert = FALSE) grepl(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

虽然参数看起差不多,但是返回的结果不一样。下来例子列出C:\windows目录下的所有文件,然后用grep和grepl查找exe文件:

files <- list.files("c:/windows") grep("\\.exe$", files)

## [1] 8 28 30 35 36 58 69 99 100 102 111 112 115 117

grepl("\\.exe$", files)

## [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
## [12] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [23] FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE
## [34] FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [45] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [56] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [67] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [78] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [89] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
## [100] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [111] TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE

grep仅返回匹配项的下标,而grepl返回所有的查询结果,并用逻辑向量表示有没有找到匹配。两者的结果用于提取数据子集的结果都一样:

files[grep("\\.exe$", files)]

## [1] "bfsvc.exe" "explorer.exe" "fveupdate.exe" "HelpPane.exe" ## [5] "hh.exe" "notepad.exe" "regedit.exe" "twunk_16.exe" ## [9] "twunk_32.exe" "uninst.exe" "winhelp.exe" "winhlp32.exe" ## [13] "write.exe" "xinstaller.exe"

files[grepl("\\.exe$", files)]

## [1] "bfsvc.exe" "explorer.exe" "fveupdate.exe" "HelpPane.exe" ## [5] "hh.exe" "notepad.exe" "regedit.exe" "twunk_16.exe" ## [9] "twunk_32.exe" "uninst.exe" "winhelp.exe" "winhlp32.exe" ## [13] "write.exe" "xinstaller.exe"

5.2 regexpr、gregexpr和regexec
这三个函数返回的结果包含了匹配的具体位置和字符串长度信息,可以用于字符串的提取操作。

text <- c("Hellow, Adam!", "Hi, Adam!", "How are you, Adam.") regexpr("Adam", text)

## [1] 9 5 14 ## attr(,"match.length") ## [1] 4 4 4 ## attr(,"useBytes") ## [1] TRUE

gregexpr("Adam", text)

## [[1]]
## [1] 9
## attr(,"match.length")
## [1] 4 ## attr(,"useBytes")
## [1] TRUE ## ## [[2]] ## [1] 5
## attr(,"match.length")
## [1] 4
## attr(,"useBytes")
## [1] TRUE
## ## [[3]]
## [1] 14
## attr(,"match.length")
## [1] 4
## attr(,"useBytes")
## [1] TRUE

regexec("Adam", text)

## [[1]]
## [1] 9
## attr(,"match.length")
## [1] 4
## ## [[2]]
## [1] 5
## attr(,"match.length")
## [1] 4
## ## [[3]]
## [1] 14
## attr(,"match.length")
## [1] 4

6 字符串替换
6.1 sub和gsub函数
虽然sub和gsub是用于字符串替换的函数,但严格地说R语言没有字符串替换的函数,因为R语言不管什么操作对参数都是传值不传址。

text

## [1] "Hellow, Adam!" "Hi, Adam!" "How are you, Adam."

sub(pattern = "Adam", replacement = "world", text)

## [1] "Hellow, world!" "Hi, world!" "How are you, world."

text

## [1] "Hellow, Adam!" "Hi, Adam!" "How are you, Adam."

可以看到:虽然说是“替换”,但原字符串并没有改变,要改变原变量我们只能通过再赋值的方式。 sub和gsub的区别是前者只做一次替换(不管有几次匹配),而gsub把满足条件的匹配都做替换:

sub(pattern = "Adam|Ava", replacement = "world", text)

## [1] "Hellow, world!" "Hi, world!" "How are you, world."

gsub(pattern = "Adam|Ava", replacement = "world", text)

## [1] "Hellow, world!" "Hi, world!" "How are you, world."

sub和gsub函数可以使用提取表达式(转义字符+数字)让部分变成全部:

sub(pattern = ".*(Adam).*", replacement = "\\1", text)

## [1] "Adam" "Adam" "Adam"

7 字符串提取
7.1 substr和substring函数
substr和substring函数通过位置进行字符串拆分或提取,它们本身并不使用正则表达式,但是结合正则表达式函数regexpr、gregexpr或regexec使用可以非常方便地从大量文本中提取所需信息。两者的参数设置基本相同:

substr(x, start, stop) substring(text, first, last = 1000000L)
x均为要拆分的字串向量
start/first 为截取的起始位置向量
stop/last 为截取字串的终止位置向量
但它们的返回值的长度(个数)有差 别:
substr返回的字串个数等于第一个参数的长度
而substring返回字串个数等于三个参数中最长向量长度,短向量循环使用。
先看第1参数(要 拆分的字符向量)长度为1例子:

x <- "123456789" substr(x, c(2, 4), c(4, 5, 8))

## [1] "234"

substring(x, c(2, 4), c(4, 5, 8))

## [1] "234" "45" "2345678"

因为x的向量长度为1,所以substr获得的结果只有1个字串,即第2和第3个参数向量只用了第一个组合:起始位置2,终止位置4。 而substring的语句三个参数中最长的向量为c(4,5,8),执行时按短向量循环使用的规则第一个参数事实上就是c(x,x,x),第二个参数就成了c(2,4,2),最终截取的字串起始位置组合为:2-4, 4-5和2-8。
请按照这样的处理规则解释下面语句运行的结果:

x <- c("123456789", "abcdefghijklmnopq") substr(x, c(2, 4), c(4, 5, 8))

## [1] "234" "de"

substring(x, c(2, 4), c(4, 5, 8))

## [1] "234" "de" "2345678"

用substring函数可以很方便地把DNA/RNA序列进行三联拆分(用于蛋白质翻译):

bases <- c("A", "T", "G", "C") DNA <- paste(sample(bases, 12, replace = T), collapse = "") DNA

## [1] "GCAGCGCATATG"

substring(DNA, seq(1, 10, by = 3), seq(3, 12, by = 3))

## [1] "GCA" "GCG" "CAT" "ATG"

用regexpr、gregexpr或regexec函数获得位置信息后再进行字符串提取的操作可以自己试试看。
8 其他:
8.1 strtrim函数
用于将字符串修剪到特定的显示宽度,其用法为strtrim(x, width),返回字符串向量的长度等于x的长度。因为是“修剪”,所以只能去掉多余的字符不能增加其他额外的字符:如果字符串本身的长度小于 width,得到的是原字符串,别指望它会用空格或其他什么字符补齐:

strtrim(c("abcdef", "abcdef", "abcdef"), c(1, 5, 10))

## [1] "a" "abcde" "abcdef"

strtrim(c(1, 123, 1234567), 4)

## [1] "1" "123" "1234"

8.2 strwrap函数
该函数把一个字符串当成一个段落的文字(不管字符串中是否有换行符),按照段落的格式(缩进和长度)和断字方式进行分行,每一行是结果中的一个字符串。例如:

str1 <- "Each character string in the input is first split into paragraphs\n(or lines containing whitespace only). The paragraphs are then\nformatted by breaking lines at word boundaries. The target\ncolumns for wrapping lines and the indentation of the first and\nall subsequent lines of a paragraph can be controlled\nindependently." str2 <- rep(str1, 2)strwrap(str2, width = 80, indent = 2)

## [1] " Each character string in the input is first split into paragraphs (or lines"
## [2] "containing whitespace only). The paragraphs are then formatted by breaking"
## [3] "lines at word boundaries. The target columns for wrapping lines and the"
## [4] "indentation of the first and all subsequent lines of a paragraph can be"
## [5] "controlled independently."
## [6] " Each character string in the input is first split into paragraphs (or lines"
## [7] "containing whitespace only). The paragraphs are then formatted by breaking"
## [8] "lines at word boundaries. The target columns for wrapping lines and the"
## [9] "indentation of the first and all subsequent lines of a paragraph can be"
## [10] "controlled independently."

simplify参数用于指定结果的返回样式,默认为TRUE,即结果中所有的字符串都按顺序放在一个字符串向量中(如上);如果为FALSE,那么结果将是列表。另外一个参数exdent用于指定除第一行以外的行缩进:

strwrap(str1, width = 80, indent = 0, exdent = 2)

## [1] "Each character string in the input is first split into paragraphs (or lines"
## [2] " containing whitespace only). The paragraphs are then formatted by breaking"
## [3] " lines at word boundaries. The target columns for wrapping lines and the"
## [4] " indentation of the first and all subsequent lines of a paragraph can be"
## [5] " controlled independently."

8.3 match和charmatch

match("xx", c("abc", "xx", "xxx", "xx"))

## [1] 2

match(2, c(3, 1, 2, 4))

## [1] 3

charmatch("xx", "xx")

## [1] 1

charmatch("xx", "xxa")

## [1] 1

charmatch("xx", "axx")

## [1] NA

match按向量进行运算,返回第一次匹配的元素的位置(如果有),非字符向量也可用。charmatch函数真坑爹。其他不看了,其实有正则表达式就足够。

 

 

 

=================================

据说还有一个stringr包,将原本的字符处理函数进行了打包,统一了函数名和参数。在增强功能基础上,还能处理向量化数据并兼容非字符数据。stringr包号称能让处理字符的时间减少95%。下面将其中的一些主要函数罗列一下。

library(stringr)

# 合并字符串
fruit <- c("apple","banana","pear","pinapple")
res <- str_c(1:4,fruit,sep=‘ ‘,collapse=‘ ‘)
str_c(‘I want to buy ‘,res,collapse=‘ ‘)

# 计算字符串长度
str_length(c("i","like","programming R",123,res))

# 按位置取子字符串
str_sub(fruit,1,3)
# 子字符串重新赋值
capital <-toupper(str_sub(fruit,1,1))
str_sub(fruit,rep(1,4),rep(1,4))<- capital

# 重复字符串
str_dup(fruit,c(1,2,3,4))

# 加空白
str_pad(fruit,10,"both")
# 去除空白
str_trim(fruit)

#  根据正则表达式检验是否匹配
str_detect(fruit,"a$")
str_detect(fruit,"[aeiou]")

# 找出匹配的字符串位置
str_locate(fruit,"a")

# 提取匹配的部分
str_extract(fruit,"[a-z]+")
str_match(fruit,"[a-z]+")

# 替换匹配的部分
str_replace(fruit,"[aeiou]","-")

# 分割
str_split(res," ")

R语言学习笔记:字符串处理

标签:style   io   os   ar   使用   for   sp   文件   数据   

原文地址:http://www.cnblogs.com/speeding/p/4067846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!