Announcement Icon Online training class for Clinical R programming batch starts on Monday, 02Feb2026. Click here for details.

Convert Between Character and Numeric Variables


Lesson Description
-
  • Sometimes, we want to work with the concept of "Convert Between Character and Numeric Variables" in a clear, repeatable way.
  • This lesson walks through a simple example and shows the key steps.
  • We will see one approach on how we can do it in SAS and R.

 


data convert;
    input id $ char_num $ num_val;
    datalines;
1  100    55
2  200    60
3  ABC    65
4  300    .
5  .      75
;
run;

data convert2;
    set convert;

    
* Convert character to numeric;
    char_to_num = input(char_num, 
best.);

    
* Convert numeric to character;
    num_to_char = put(num_val, 
best.);
run;
  • The dataset `convert` includes both character and numeric variables to demonstrate type conversions.
  • `input(char_num, best.)` converts the character variable `char_num` to a numeric value. Invalid strings like 'ABC' become missing.
  • `put(num_val, best.)` converts the numeric variable `num_val` into a character string.
  • The resulting variables `char_to_num` and `num_to_char` reflect the converted values.
convert <- tribble(
~id, ~char_num, ~num_val,
"1", "100", 55,
"2", "200", 60,
"3", "ABC", 65,
"4", "300", NA,
"5", NA, 75 )

 
convert2 <- convert %>%
   mutate( char_to_num = as.numeric(char_num),
     num_to_char = as.character(num_val)
)
  • The dataset `convert` includes both character and numeric values with intentional missing and invalid entries.
  • `as.numeric(char_num)` converts `char_num` to numeric.
  • Non-numeric text like 'ABC' becomes `NA`. `as.character(num_val)` converts numeric values to character strings.
  • The new columns `char_to_num` and `num_to_char` reflect these conversions.
convert <- data.frame(
  id = c("1", "2", "3", "4", "5"),
  char_num = c("100", "200", "ABC", "300", NA),
  num_val = c(55, 60, 65, NA, 75)
  , stringsAsFactors = FALSE
)

convert2 <- convert

convert2$char_to_num <- as.numeric(convert2$char_num)

convert2$num_to_char <- as.character(convert2$num_val)
  • as.numeric() converts strings to numbers (invalid values become NA).
  • as.character() converts numeric values to strings.