R中的字符串–函数及其操作
字符串通常是一维(1D)数组,其中包含单个或者多个值。
字符串可以包括字符数据,数字数据以及任何特殊字符。
R中的字符串–简介
字符串不过是R中用双引号""括起来的值。
它可以是单个值或者多个。
同时,空字符串用""表示。
您应该用双引号""表示字符串,也可以在字符串之间使用单引号。
字符串的简单说明如下。
#A simple string in R df<-"journal dev - R tutorials"
注意:不能在双引号内使用双引号,也不能在单引号字符串内使用单引号。
字符串构造规则
这里有一些构造字符串的通用规则。
- 开头和结尾引号应该相同
- 您可以在双引号之间使用单引号
- 您可以在单引号之间使用双引号
- 您不能在单引号之间使用单引号
- 您不能在双引号之间使用双引号
R中的有效字符串
有效字符串是根据字符串规则遵循并构造的字符串。
以下是一些有效字符串的示例。
x<- "ANOVA in R"
输出=" R中的ANOVA"
y<-'www.theitroad.local'
输出=" www.theitroad.local"
df<- "R tutorials 'R programming'in JD"
输出=" JD中的R教程'R编程'
df<-'string "function" in R'
输出=" R中的字符串" function "
R中的无效字符串
如果有任何字符串违反规则,则它将成为无效字符串。
下面列出了一些无效的字符串。
#quotes mix up x<- "ANOVA in R'
输出=
错误:" x <-" ANOVA"中出现意外符号
#use of double quotes inside double quotes y<-"R programming "tutorials" is here"
输出=错误:" y <-" R编程"教程"中的意外符号
如您所见,上面的示例也将使您了解错误和无效的字符串。
R中的字符串操作
在本节中,我们将在各个方面对R中的字符串进行操作,如下所示。
paste()–连接字符串。
format()–格式化数值。
nchar()–计算字符串中的字符。
substring()–从字符串中提取特定字符。
我们将看到上述这些函数如何操作字符串。
paste()函数连接字符串。
使用paste()函数,您可以轻松地连接或者组合字符串。
paste()函数能够将多个元素作为输入并将它们串联成一个字符串。
要了解有关R中的paste()函数的更多信息:R中的paste()
让我们看看它是如何工作的。
#creates a string w<-'welcome' x<-'to' y<-'Journal dev' z<-'R programming tutorials' #concatenates the strings in to a single string paste(w,x,y,z,sep = '_')
输出=" welcome_to_Journal dev_R编程教程"
在R中使用format()函数进行字符串格式化
在R中,您可以在各个方面设置数字格式,如下所示。
让我们看看format()函数如何工作。
#formats the number count df<-format(23.45788,digits = 5)
输出=" 23.458"
#formats the scientific values df<-format(c(23,67.890),scientific = T)
输出=" 2.300e + 01"" 6.789e + 01"
#formats the decimal values format(34.8,nsmall = 5)
输出=" 34.80000"
#formats the number space format(34.8,width=10)
输出=" 34.8"
#formats the number alignment to left format("JD",width = 10,justify = 'l')
输出=" JD"
#formats the number alignment to right format("JD",width = 10,justify = 'r')
输出=" JD"
##formats the number alignment to centre format("JD",width = 10,justify = 'c')
输出=" JD"
使用nchar()函数计算字符串中的字符数
R具有名为nchar()的函数,该函数也计算给定字符串中存在的字符数。
让我们看看它是如何工作的。
语法:
nchar(x)
让我向您展示如何使用nchar()计数字符串中存在的数字字符。
nchar("R programming tutorials")
输出= 23
nchar("R is a statistical analysis language")
输出= 36
使用toupper()和tolower()函数更改字符串的大小写
在R中,您可以使用tolower()和toupper()函数轻松地将字符串的大小写从大写改为小写,反之亦然。
语法如下:
- 上衣(x)
- 降低(x)
其中,x =输入字符串
toupper("R is a statistical analysis language")
输出=" R是一种统计分析语言"
tolower("R IS A STATISTICAL ANALYSIS LANGUAGE")
输出=" r是一种统计分析语言"
R中的substring()函数
R中的substring()函数用于从字符串中提取数据或者字符。
下图将定义R中substring()的工作方式。
#extractes the specific charater range from the string substring("theitroad",8,11)
输出=" dev"
在substring()函数中,第一个数字和第二个数字表示要从字符串中提取的索引号的开头和结尾,如上所示。
#extractes the specific charater range from the string substring("theitroad",1,7)