R Tutorial



R TYPE CONVERSION


Type Conversion in R

Type conversion (also called type casting) in R means converting data from one type to another. This is useful when you need to perform operations that require specific data types or when cleaning data.

Common Type Conversion Functions

  • as.numeric(x) – Converts x to numeric (double) type.
  • as.integer(x) – Converts x to integer type.
  • as.character(x) – Converts x to character string.
  • as.logical(x) – Converts x to logical (TRUE/FALSE).
  • as.factor(x) – Converts x to factor type (used for categorical data).

Example: Type Conversion

x <- "123"
y <- 45.67
z <- 1

# Convert character to numeric
num_x <- as.numeric(x)
print(num_x)            # 123

# Convert numeric to integer
int_y <- as.integer(y)
print(int_y)            # 45

# Convert numeric to character
char_y <- as.character(y)
print(char_y)           # "45.67"

# Convert numeric to logical
log_z <- as.logical(z)
print(log_z)            # TRUE

# Convert character to factor
fact_x <- as.factor(x)
print(fact_x)           # Factor with levels "123"
  

Important Notes

  • If conversion is not possible, R returns NA with a warning.
  • Logical values convert as TRUE → 1 and FALSE → 0 when cast to numeric.
  • Factors are stored internally as integers but represent categorical data with labels.

💡 Quick Tip:

Always check your data types after conversion with class() or typeof() to avoid unexpected errors.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review