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.
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).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"
NA
with a warning.TRUE → 1
and FALSE → 0
when cast to numeric.💡 Quick Tip:
Always check your data types after conversion with class()
or typeof()
to avoid unexpected errors.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!