create vector in r logical integer double character

R – Vectors: Logical, Integer, Double, and Character

Posted on

How To Create Logical, Integer, Double, and Character Vectors

R Logical Vectors

R Logical Vector is a vector consists of items whose type is “logical” . This logical value is either TRUE or FALSE. The items can also have a value of NA.

Example 1:

m <- c(TRUE,TRUE,FALSE,FALSE,NA,NA)
print(typeof(m))
print(m)

#output:
[1] "logical"
[1]  TRUE  TRUE FALSE FALSE    NA    NA

Example 2:

m <- c(3, 4, 5, 6, 7)
result <- m%%2 == 0
print(result)

#output:
[1] FALSE  TRUE FALSE  TRUE FALSE

R Integer Vectors

R Integer Vector is a vector consists of items whose type is “integer” . The items can have a value of Integer or NA.

A number by default is considered double in R. But it can be considered as Integer by having the number followed by the character L.

Example 1 – Integer value:

m1 <- c(1, 7, 5, 9, 12)
print(typeof(m1))
print(m1)
m2 <- c(1L, 7L, 5L, 9L, 12L)
print(typeof(m2))
print(m2)

#output:
[1] "double"
[1]  1  7  5  9 12
[1] "integer"
[1]  1  7  5  9 12

Example 2 – NA value:

m3 <- c(1L, NA, 5L, NA, 12L)
print(typeof(m3))
print(m3)

#output:
[1] "integer"
[1]  1 NA  5 NA 12

R Double Vectors

R Integer Vector is a vector consists of items whose type is “double” . The items can have a value of double or special values like NA (Missing Value), NaN (Not a Number), Inf (Positive Infinity) or -Inf (Negative Infinity).

A number by default is considered double in R Progamming.

Example:

m1 <- c(1, 7, 5, 9, 12)
print(typeof(m1))
print(m1)

m2 <- c(1, NA, NaN, Inf, -Inf)
print(typeof(m2))
print(m2)

#output:
[1] "double"
[1]  1  7  5  9 12

[1] "double"
[1]    1   NA  NaN  Inf -Inf

R Character Vectors

R Integer Vector is a vector consists of items whose type is “character” . The items can have a value of String or NA (Missing Value).

Example:

m1 <- c("j", "k", "l", "m", "n")
print(typeof(m1))
print(m1)

m2 <- c("j", NA, NA, "m", "2")
print(typeof(m2))
print(m2)

#output:
[1] "character"
[1] "j" "k" "l" "m" "n"

[1] "character"
[1] "j" NA  NA  "m" "2"

Conclusions:

There are four types of vectors which are Logical, Integer, Double, and Character Vectors. All the vector types allow the value NA (Missing value) on it’s items.