Menu
Coddy logo textTech

Data Type Conversion

Lesson 4 of 14 in Coddy's Data Manipulation in R course.

Data type conversion is allowing you to transform data between different types to suit your analysis needs. In this lesson, we'll focus on converting between numeric, character, and factor data types.

Checking Data Types

Before converting, it's important to know the current data type of your variable. Use the class() function to check:

x <- 42
class(x)  # Output: "numeric"

y <- "Hello"
class(y)  # Output: "character"

Numeric to Character Conversion

Use the as.character() function to convert numeric to character:

num <- 42
char_num <- as.character(num)
class(char_num)  # Output: "character"
print(char_num)  # Output: "42"

Character to Numeric Conversion

Use the as.numeric() function to convert character to numeric:

char <- "3.14"
num_char <- as.numeric(char)
class(num_char)  # Output: "numeric"
print(num_char)  # Output: 3.14

Character to Factor Conversion

Use the as.factor() function to convert character to factor:

fruits <- c("apple", "banana", "apple", "cherry")
factor_fruits <- as.factor(fruits)
class(factor_fruits)  # Output: "factor"
print(factor_fruits)  # Output: apple banana apple cherry
                      #         Levels: apple banana cherry

Factor to Character Conversion

Use the as.character() function to convert factor to character:

char_fruits <- as.character(factor_fruits)
class(char_fruits)  # Output: "character"
print(char_fruits)  # Output: "apple" "banana" "apple" "cherry"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

performs the following data type conversions and operations:

  1. Convert a numeric vector to a character vector
  2. Convert a character vector to a factor
  3. Convert the factor back to a character vector
  4. Calculate the mean of the original numeric vector

Try it yourself

# Read input
con <- file("stdin", "r")
input_string <- suppressWarnings(readLines(con))

# Convert input string to numeric vector
numeric_vector <- as.numeric(strsplit(input_string, ",")[[1]])

# TODO: Write your code below

# 1. Convert numeric_vector to a character vector
# 2. Convert the character vector to a factor
# 3. Convert the factor back to a character vector
# 4. Calculate the mean of the original numeric vector
char_vector <- ?
factor_vector <- ?
char_from_factor <- ?
mean_value <- ?

# Print the result
print(numeric_vector)
print(char_vector)
print(factor_vector)
print(char_from_factor)
print(mean_value)

All lessons in Data Manipulation in R