R(11), String

Published: by Creative Commons Licence

String

connect string

paste(): connect string

paste(..., sep = " ", collapse = NULL)
  • ... represents any number of arguments to be combined.
  • sep represents any separator between parameters. It's optional.
  • collapse remove spaces between two strings. But not a string of two words within the space.
a <- "Hello"
b <- 'How'
c <- "are you? "

print(paste(a,b,c))
print(paste(a,b,c, sep = "-"))
print(paste(a,b,c, sep = "", collapse = ""))

results:

[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "

Format Numbers and Strings

format(): formats numbers and strings to specific styles.

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))
  • x: input vector
  • digits: total number of digits displayed
  • nsmall: the minimum number of digits to the right of the decimal point
  • scientific = TRUE, display scientific notation
  • width: The minimum width to display by filling the beginning with a blank
  • justify: left, right or center display.

more

the Number of Characters

nchar(): Calculate the Number of Characters in a String

nchar(x)

x: input vector

Case Changing

toupper(x)
tolower(x)

Substring

substring(): extract part of string

substring(x,first,last)

example:

# Extract characters from 5th to 7th position.
result <- substring("Extract", 5, 7)
print(result)

result:

[1] "act"