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: 50This 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
EasyRead two numeric values as input, perform a calculation, and display the result with a label.
You will receive two inputs:
- A price (as a string)
- 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: 62Cheat sheet
Use as.numeric() to convert a character string to a number:
input <- "42"
number <- as.numeric(input)
cat(number + 8, "\n") # Output: 50Common 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"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values