Logical and Character Conversion
Convert between logical, character, and numeric with as.logical() and as.character().
Logical and Character Conversion is a free R Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
Converting Between Types
R provides as.*() functions for converting between all basic types. This lesson covers conversions between logical, character, and numeric types — the most common round-trip conversions you will encounter in data cleaning.
# Quick overview of as.*() functions
cat('as.logical(1): ', as.logical(1), '
') # TRUE
cat('as.numeric(TRUE): ', as.numeric(TRUE), '
') # 1
cat('as.character(3.14):', as.character(3.14), '
') # "3.14"
cat('as.logical("TRUE"):', as.logical('TRUE'), '
') # TRUENumeric to Logical
Converting a number to logical: 0 becomes FALSE, any non-zero number becomes TRUE. This rule applies to both integers and doubles.
cat('as.logical(0): ', as.logical(0), '
') # FALSE
cat('as.logical(1): ', as.logical(1), '
') # TRUE
cat('as.logical(-5): ', as.logical(-5), '
') # TRUE (non-zero)
cat('as.logical(0.001):', as.logical(0.001), '
') # TRUE (non-zero)
cat('as.logical(0L): ', as.logical(0L), '
') # FALSE
cat('as.logical(3L): ', as.logical(3L), '
') # TRUELogical to Numeric
TRUE converts to 1 and FALSE to 0. This conversion is at the heart of many R idioms — like using sum() to count TRUE values or mean() to compute proportions.
cat('as.numeric(TRUE): ', as.numeric(TRUE), '
') # 1
cat('as.numeric(FALSE): ', as.numeric(FALSE), '
') # 0
cat('as.integer(TRUE): ', as.integer(TRUE), '
') # 1L
# Practical use: count TRUEs by summing
passed <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE)
cat('Passed count:', sum(as.numeric(passed)), '
') # 4
cat('Pass rate: ', mean(passed) * 100, '%
') # 66.67%as.logical() from Strings
as.logical('TRUE') and as.logical('FALSE') convert string representations. R also accepts 'T' and 'F' as abbreviations. Anything else (including 'true' lowercase) returns NA.
cat('as.logical("TRUE"): ', as.logical('TRUE'), '
') # TRUE
cat('as.logical("FALSE"): ', as.logical('FALSE'), '
') # FALSE
cat('as.logical("T"): ', as.logical('T'), '
') # TRUE
cat('as.logical("F"): ', as.logical('F'), '
') # FALSE
cat('as.logical("yes"): ', as.logical('yes'), '
') # NA (not recognised)
cat('as.logical("true"): ', as.logical('true'), '
') # NA (case-sensitive!)Numeric to Character
as.character(x) converts a number to its string representation. This is useful for creating labels, IDs, or when you need to paste numbers into strings.
num_val <- 3.14159
char_val <- as.character(num_val)
cat('as.character(3.14159):', char_val, '
') # '3.14159'
cat('class:', class(char_val), '
') # character
# Building labels
ids <- 1:5
labels <- paste0('Item_', as.character(ids))
cat('Labels:', labels, '
')Character to Numeric
as.numeric('3.14') parses a string into a double. If the string cannot be interpreted as a number, R returns NA with a warning. Always validate input before conversion in production code.
cat('as.numeric("3.14"): ', as.numeric('3.14'), '
') # 3.14
cat('as.numeric("100"): ', as.numeric('100'), '
') # 100
cat('as.numeric("-5.5"): ', as.numeric('-5.5'), '
') # -5.5
cat('as.numeric("abc"): ', as.numeric('abc'), '
') # NA with warning
cat('as.numeric("1e3"): ', as.numeric('1e3'), '
') # 1000 (sci notation OK)Logical to Character
as.character(TRUE) produces the string 'TRUE'. This is useful when you need to include logical values in text output, file exports, or string concatenations.
flag_t <- TRUE
flag_f <- FALSE
cat('as.character(TRUE): ', as.character(flag_t), '
') # 'TRUE'
cat('as.character(FALSE):', as.character(flag_f), '
') # 'FALSE'
cat('class:', class(as.character(flag_t)), '
') # character
# In paste()
message <- paste('System status:', as.character(flag_t))
cat(message, '
')Round-Trip Conversion
Most conversions are reversible (round-trip), but with some loss: numeric -> character -> numeric may lose precision depending on how the number is formatted as a string.
original <- 3.141592653589793
char_version <- as.character(original)
back_to_num <- as.numeric(char_version)
cat('Original: ', original, '
')
cat('As string: ', char_version, '
')
cat('Back: ', back_to_num, '
')
cat('Identical?:', identical(original, back_to_num), '
')
cat('Equal?: ', original == back_to_num, '
')Converting Vectors of Mixed Origin
When you apply as.numeric() to a character vector, each element is converted independently. Elements that cannot be parsed become NA. This is the standard way to clean numeric-looking data read from CSV files.
# Simulated data from CSV (all read as character)
raw_data <- c('42', '37.5', 'N/A', '55', '', '28.0')
cat('Raw character data:', raw_data, '
')
numeric_data <- suppressWarnings(as.numeric(raw_data))
cat('Converted: ', numeric_data, '
') # 42 37.5 NA 55 NA 28
cat('NA count: ', sum(is.na(numeric_data)), '
')Logical Conversion in ifelse()
Combining as.numeric() with ifelse() or direct multiplication by a logical vector is a common idiom for conditional scoring or feature engineering in data analysis.
# Score: 1 for correct, 0 for incorrect
quiz_answers <- c('A', 'C', 'B', 'D', 'B')
correct <- c('A', 'B', 'B', 'D', 'C')
is_correct <- quiz_answers == correct
cat('Correct: ', is_correct, '
')
cat('As 0/1: ', as.numeric(is_correct), '
')
cat('Score: ', sum(is_correct), '/', length(is_correct), '
')Conversion Summary
Here is a summary of key logical and character conversions:
as.logical(0)→FALSE; any non-zero →TRUEas.logical('TRUE'/'T')→TRUE; case-sensitive; others →NAas.numeric(TRUE)→1;as.numeric(FALSE)→0as.character(x)→ string representation of xas.numeric('3.14')→ 3.14; non-numeric strings →NAwith warning
# All conversions in one snippet
cat('logical->num: ', as.numeric(c(TRUE, FALSE)), '
')
cat('num->logical: ', as.logical(c(0, 1, -1, 0.5)), '
')
cat('char->num: ', suppressWarnings(as.numeric(c('5', 'abc', '3.1'))), '
')
cat('char->logical: ', as.logical(c('TRUE', 'FALSE', 'yes')), '
')
cat('logical->char: ', as.character(c(TRUE, FALSE)), '
')Quick Check
What does as.numeric(TRUE) + as.numeric(FALSE) evaluate to in R?
Recap: Logical and Character Conversion
Excellent! Key takeaways from this lesson:
as.logical(0)→FALSE; non-zero →TRUE;'TRUE'/'T'→TRUEas.numeric(TRUE)→1;as.numeric(FALSE)→0as.character(x)converts any value to its string formas.numeric('3.14')parses a numeric string; invalid strings →NAas.logical('true')isNA— the match is case-sensitive ('TRUE'works)- Conversions are mostly reversible; use
suppressWarnings()when converting columns with expected NA-producing entries
# Practical: parse a messy survey score column
raw_scores <- c('8', '7', 'N/A', '9', 'skip', '6')
numeric_scores <- suppressWarnings(as.numeric(raw_scores))
cat('Parsed:', numeric_scores, '
')
cat('Valid responses:', sum(!is.na(numeric_scores)), '
')
cat('Average score: ', round(mean(numeric_scores, na.rm = TRUE), 2), '
')Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “Logical and Character Conversion” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “Logical and Character Conversion”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “Logical and Character Conversion”?
Convert between logical, character, and numeric with as.logical() and as.character(). You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Logical and Character Conversion” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- R's Type System Overview
- Converting Between Numeric Types
- Logical and Character Conversion
- Coercion Pitfalls and Best Practices