2024

Variable Types in R

R supports various variable types, each with its own characteristics. Understanding these types is crucial for data manipulation and analysis.

Numeric

  • The default computational data type.
  • Used for real numbers.
# Example of numeric type
a <- 3.14
class(a)
## [1] "numeric"

Integer

  • Used for integer values.
  • Specify integers by appending L to the number.
# Example of integer type
b <- 42L
class(b)
## [1] "integer"

Character

  • Used for text or string data.
  • Enclose the text in single or double quotes.
# Example of character type
c <- "Hello, R!"
class(c)
## [1] "character"

Logical

  • Represents boolean values: TRUE or FALSE.
  • Used for conditional testing.
# Example of logical type
d <- TRUE
class(d)
## [1] "logical"

Factors

  • Used to handle categorical data.
  • Stores both the levels and the values.
# Example of factor type
e <- factor(c("Low", "Medium", "High"), levels = c("Low", "Medium", "High"))
class(e)
## [1] "factor"
levels(e)
## [1] "Low"    "Medium" "High"

Practive Question 1

What is the class of the variable defined by x <- 2.5?

  1. integer
  2. numeric
  3. character
  4. logical
Click here for the answer The correct answer is 2. numeric. R treats numbers with decimal points as numeric.

Practice Question 2

Which of the following is the correct way to create a character variable containing the text “R is fun”?

  1. x <- R is fun
  2. x <- "R is fun"
  3. x <- c(R is fun)
  4. x <- 'R' 'is' 'fun'
Click here for the answer The correct answer is 2. x <- "R is fun". Text must be enclosed in quotes to be treated as character data in R.

Practice Question 3

True or False: The expression class(100L) will return integer.

Click here for the answer True. Appending L to a number specifies it as an integer in R.

Practice Question 4

How do you specify a logical variable in R?

  1. x <- logical
  2. x <- "TRUE"
  3. x <- TRUE
  4. x <- T
Click here for the answer The correct answer is 3. x <- TRUE. However, 4. x <- T is also technically correct as T is shorthand for TRUE in R, but using TRUE is preferred for clarity.

Practice Question 5

Which function is used to create factors in R?

  1. factor()
  2. as.factor()
  3. createFactor()
  4. Both 1 and 2 are correct
Click here for the answer The correct answer is 4. Both 1 and 2 are correct. factor() creates a factor, and as.factor() converts an existing variable to a factor.