A variable, hello, is defined. It is a character vector of length 1.
hello <- "Hello World!"
print(hello)
## [1] "Hello World!"
Here we have 2 character vectors, both of length 1. All vectors can only contain one kind of data, such as numbers or strings. We will use the paste function to join the two character vectors.
hello <- "Hello"
world <- "World!"
hello.world <- paste(hello,world)
print(hello.world)
## [1] "Hello World!"
We can find length of vectors:
len.hello <- length(hello)
len.world <- length(world)
len.hello.world <- length(hello.world)
print(len.hello)
## [1] 1
print(len.world)
## [1] 1
print(len.hello.world)
## [1] 1
We can format strings with sprintf with flags such as %s (string) and %d (integer)
str1 <- sprintf("The length of hello.world is %d", len.hello.world)
print(str1)
## [1] "The length of hello.world is 1"
We can find the number of characters in a character vector using nchar. The first character vector is of length 1, so only 1 number is returned by nchar. The next character vector is of length 2, and thus we get 2 numbers for nchar. The c(), the combine function, is often used to make vectors of lengths greater than 1.
num.char <- nchar(hello.world)
print(num.char)
## [1] 12
hello.2.world <- c("Hello","World!")
print(length(hello.2.world))
## [1] 2
print(nchar(hello.2.world))
## [1] 5 6