Convert between characters and ASCII codes

asc(char, simplify = TRUE)

chr(ascii)

Arguments

char

vector of character strings

simplify

logical indicating whether to attempt to convert the result into a vector or matrix object. See sapply for details.

ascii

vector or list of vectors containing integer ASCII codes

Value

asc returns the integer ASCII values for each character in the elements of char. If simplify=FALSE the result will be a list containing one vector per element of char. If simplify=TRUE, the code will attempt to convert the result into a vector or matrix.

asc returns the characters corresponding to the provided ASCII values.

Functions

  • asc(): return the characters corresponding to the specified ASCII codes

  • chr(): return the ASCII codes for the specified characters.

Author

Adapted by Gregory R. Warnes greg@warnes.net from code posted by Mark Davis on the 'Data Debrief' blog on 2011-03-09 at https://datadebrief.blogspot.com/2011/03/ascii-code-table-in-r.html.

Examples


## ascii codes for lowercase letters
asc(letters)
#>   a   b   c   d   e   f   g   h   i   j   k   l   m   n   o   p   q   r   s   t 
#>  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 
#>   u   v   w   x   y   z 
#> 117 118 119 120 121 122 

## uppercase letters from ascii codes
chr(65:90)
#>  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#> [20] "T" "U" "V" "W" "X" "Y" "Z"

## works on muti-character strings
(tmp <- asc("hello!"))
#>      hello!
#> [1,]    104
#> [2,]    101
#> [3,]    108
#> [4,]    108
#> [5,]    111
#> [6,]     33
chr(tmp)
#> [1] "h" "e" "l" "l" "o" "!"

## Use 'simplify=FALSE' to return the result as a list
(tmp <- asc("hello!", simplify = FALSE))
#> $`hello!`
#> [1] 104 101 108 108 111  33
#> 
chr(tmp)
#>   hello! 
#> "hello!" 

## When simplify=FALSE the results can be...
asc(c("a", "e", "i", "o", "u", "y")) # a vector
#>   a   e   i   o   u   y 
#>  97 101 105 111 117 121 
asc(c("ae", "io", "uy")) # or a matrix
#>       ae  io  uy
#> [1,]  97 105 117
#> [2,] 101 111 121

## When simplify=TRUE the results are always a list...
asc(c("a", "e", "i", "o", "u", "y"), simplify = FALSE)
#> $a
#> [1] 97
#> 
#> $e
#> [1] 101
#> 
#> $i
#> [1] 105
#> 
#> $o
#> [1] 111
#> 
#> $u
#> [1] 117
#> 
#> $y
#> [1] 121
#> 
asc(c("ae", "io", "uy"), simplify = FALSE)
#> $ae
#> [1]  97 101
#> 
#> $io
#> [1] 105 111
#> 
#> $uy
#> [1] 117 121
#>