Convert between characters and ASCII codes

Share:

Description

asc returns the ASCII codes for the specified characters. chr returns the characters corresponding to the specified ASCII codes.

Usage

1
2
  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 contining 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.

Author(s)

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

See Also

strtoi, charToRaw, rawToChar, as.raw

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  ## ascii codes for lowercase letters
  asc(letters)

  ## uppercase letters from ascii codes
  chr(65:90)

  ## works on muti-character strings
  ( tmp <- asc('hello!') )
  chr(tmp)

  ## Use 'simplify=FALSE' to return the result as a list
  ( tmp <- asc('hello!', simplify=FALSE) )
  chr(tmp)

  ## When simplify=FALSE the results can be...
  asc( c('a', 'e', 'i', 'o', 'u', 'y' ) ) # a vector
  asc( c('ae', 'io', 'uy' ) )             # or a matrix

  ## When simplify=TRUE the results are always a list...
  asc( c('a', 'e', 'i', 'o', 'u', 'y' ), simplify=FALSE )
  asc( c('ae', 'io', 'uy' ), simplify=FALSE)

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.