Menu
Coddy logo textTech

Type Conversion Basics

Part of the Fundamentals section of Coddy's R journey — lesson 30 of 78.

As mentioned in the previous lesson, readline() always returns a character string. If a user types "25", you get the text "25", not the number 25. This matters because you can't do math with text.

To convert a character string to a number, use as.numeric():

input <- "42"
number <- as.numeric(input)

cat(number + 8, "\n")  # Output: 50

This is essential when working with user input. Here's a common pattern you'll use:

age_text <- readline()
age <- as.numeric(age_text)

cat("In 10 years, you will be", age + 10, "\n")

You can also convert in the opposite direction using as.character():

number <- 100
text <- as.character(number)

cat("The value is:", text, "\n")

Converting numbers to characters is useful when you need to combine them with other text or when a function specifically requires character input. These conversion functions are your tools for moving between data types whenever your program needs it.

challenge icon

Challenge

Easy

Read two numeric values as input, perform a calculation, and display the result with a label.

You will receive two inputs:

  1. A price (as a string)
  2. A quantity (as a string)

Convert both inputs to numeric values using as.numeric(), then calculate the total cost by multiplying price by quantity.

Display the output in the following format:

Total: [result]

Use cat() for the output and include a newline character \n at the end.

For example, if the inputs are 15.50 and 4, the output should be:

Total: 62

Cheat sheet

Use as.numeric() to convert a character string to a number:

input <- "42"
number <- as.numeric(input)

cat(number + 8, "\n")  # Output: 50

Common pattern for converting user input:

age_text <- readline()
age <- as.numeric(age_text)

cat("In 10 years, you will be", age + 10, "\n")

Use as.character() to convert a number to a character string:

number <- 100
text <- as.character(number)

cat("The value is:", text, "\n")

Try it yourself

# Read input
con <- file("stdin", "r")
price_str <- suppressWarnings(readLines(con, n = 1))
quantity_str <- suppressWarnings(readLines(con, n = 1))
close(con)

# TODO: Write your code below
# 1. Convert price_str and quantity_str to numeric values using as.numeric()
# 2. Calculate the total cost (price * quantity)
# 3. Display the result using cat() with the format "Total: [result]\n"
quiz iconTest yourself

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

All lessons in Fundamentals