Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 31 / 68

The basics of type conversion (casting)

This lesson covers type conversion in R, with the aim of converting between strings and numbers.

Converting a string to a number, or a number to a string — type conversion (casting) — is a basic programming operation. You use as.integer(), as.character(), and friends.

The sample code converts the string "123" to an integer with as.integer("123") and uses it in a calculation, then converts the number 45 to a string with as.character(45) to join it to another string. Note how the conversion function is chosen to suit the purpose.

A common early stumble is that converting a string that is not a number returns NA. It is not an error — you get a warning and an NA — so using the result without checking causes trouble later.

In professional work, data read from a CSV file often arrives as text, so type conversion before calculation is a daily occurrence.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)