Let’s start coding in R: printing text, comments, variables, data types, reading input and converting between types.
What You Will Learn
- print() and quote = FALSE
- Comments
- Three ways to assign variables
- class() vs typeof()
- Reading input and converting it
Prerequisites
print("Hello World !")
print("Itronix Solutions", quote = FALSE)
[1] "Hello World !" [1] Itronix Solutions
Comments
print("Hello World 1")
# print("This line will not run")
print("Hello World 5")
[1] "Hello World 1" [1] "Hello World 5"
Explanation: Lines starting with # are ignored. R has no multi-line comment; in RStudio select lines and press Ctrl + Shift + C to comment them all.
Assign Variables
Var = 10
Var <- 20
30 -> Var
print(Var)
[1] 30
Explanation: All three assign a value; <- is the R style most people use.
Data Types
x <- 10L
print(class(x)); print(typeof(x))
x <- 28
print(class(x)); print(typeof(x))
x <- charToRaw("Hello")
print(x)
[1] "integer" [1] "integer" [1] "numeric" [1] "double" [1] 48 65 6c 6c 6f
Explanation: A plain number like 28 is stored as a double (class “numeric”); add L for an integer. charToRaw shows the bytes of a string in hexadecimal.
| Value | class() | typeof() |
|---|---|---|
| 28 | numeric | double |
| 10L | integer | integer |
| “Itronix” | character | character |
| TRUE | logical | logical |
| 2+5i | complex | complex |
Read Input and Convert
x <- readline(prompt = "Enter any number: ")
print(typeof(x))
x <- as.integer(x)
print(x * 2)
Enter any number: 10 [1] "character" [1] 20
Explanation: readline returns a character string, even for “10” or “3.14”. Convert with as.integer(), as.numeric() or as.logical() before calculating.
Series
R series: Install R · Introduction to R · R in Jupyter · Practical Session · Operators · Decision Making · Loops · Functions · Strings · cat() and paste() · Vectors · Lists · Matrices · Data Frames
Interview Questions
Q: What does readline() return?
Always a character string.
Q: What is the difference between <- and =?
Both assign; <- is the conventional R style and = is mainly used for function arguments.
Practice Exercises
- Read the radius of a circle and print its area.
- Print the class and type of 5, 5L, “5” and TRUE.
Summary
Use print() for output, # for comments and <- for assignment. Check types with class()/typeof() and convert readline() input with as.integer() or as.numeric().
Next: Operators
Machine Learning Tutorials, Courses and Certifications