官术网_书友最值得收藏!

String functions

Let's see how we can transform or convert strings using R.

The most relevant string examples are as follows:

  • To know the number of characters in a string:
nchar(c)
## [1] 24
  • To return the substring of x, originating at a particular character in x:
substring(c,4)
## [1] "s is our first string"
  • To return the substring of x originating at one character located at n and ending at another character located at a place, m:
substring(c,1,4)
## [1] "This"
  • To divide the string x into a list of sub chains using the delimiter as a separator:
strsplit(c, " ")
## [[1]]
## [1] "This" "is" "our" "first" "string"

  • To check if the given pattern is in the string, and in that case returns true (or 1):
grep("our", c)
## [1] 1
grep("book", c)
## integer(0)
  • To look for the first occurrence of a pattern in a string:
regexpr("our", c)
## [1] 9
## attr(,"match.length")
## [1] 3
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE
  • To convert the string into lowercase:
tolower(c)
## [1] "this is our first string"
  • To convert the string into capital letters:
toupper(c)
## [1] "THIS IS OUR FIRST STRING"
  • To replace the first occurrence of the pattern by the given value with a string:
sub("our", "my", c)
## [1] "This is my first string"
  • To replace the occurrences of the pattern with the given value with a string:
gsub("our", "my", c)
## [1] "This is my first string"
  • To return the string as elements of the given array, separated by the given separator using paste(string,array, sep=“Separator”):
paste(c,"My book",sep=" : ")
## [1] "This is our first string : My book"
主站蜘蛛池模板: 澄城县| 横峰县| 泸西县| 彭泽县| 太白县| 濮阳县| 高密市| 中江县| 偏关县| 印江| 渑池县| 丰台区| 建水县| 敦化市| 隆安县| 临颍县| 铜陵市| 嵊泗县| 高碑店市| 绍兴县| 呼图壁县| 洛隆县| 六枝特区| 堆龙德庆县| 龙海市| 郯城县| 恩平市| 舒兰市| 义乌市| 湘乡市| 衡水市| 江孜县| 轮台县| 岳西县| 广水市| 香格里拉县| 宜宾县| 嘉黎县| 积石山| 镇原县| 慈利县|