rsyntax

In this section, we will cover the following topics:

Writing out Text vs. Numbers

In R, to output text you will use single or double quotes:

"Hello World!"
[1] "Hello World!"
'Hello World!' 
[1] "Hello World!"

To output numbers you just type out the number. Also, note that I do not use a comma when writing out my four-digit number:

5
[1] 5
75
[1] 75
1000
[1] 1000

Basic Calculations

R at its core is a gigantic calculator, so let’s practice doing basic calculations.

# addition
10 + 2
[1] 12
# subtraction
10 - 2
[1] 8
# multipilication
10 * 2
[1] 20
# division
10/2
[1] 5
# exponent
10^2
[1] 100

Comments

It’s also important to annotate your code. It will help you write notes and explain what you are doing. To annotate your code, you will use the number sign #:

# addition
10 + 2
[1] 12
# the answer is 12

Creating Objects

In R, we save our data in what we call objects! Objects store information about different types of elements. If you know any other coding languages, they typically call these variables.

# The <- saves the caculation as math
math <- 10 + 2
#print()
print(math)
[1] 12
# The = saves the caculation as math
math = 10 + 2
# print() will print out what is saved in the object math
print(math)
[1] 12

Data Types

There are 6 types of data in R that are important to know, but the essential ones are logical, numeric, and character.

Logical Also known as boolean data, logical data is shown as TRUE or FALSE values:

logical1 <- TRUE
logical2 <- FALSE

# The class() function outputs the data type of the object
class(logical1)
[1] "logical"
print(logical2)
[1] FALSE
print(class(logical2))
[1] "logical"

Numeric represents all data types that are real numbers with or with out decimal points.

height <- 5.5
acres <- 1000

class(height)
[1] "numeric"
print(acres)
[1] 1000
print(class(acres))
[1] "numeric"

Character specifies character or string values in a variable such as a singular character ‘A’ or a string of characters in ‘Apple’.

# Use '' or "" to show it's a string of characters
motorsports <- "formula1"

print(motorsports)
[1] "formula1"
print(class(motorsports))
[1] "character"

Integer specifies real values without decimal points

# the suffix i specifies its imaginary data.
complex <- 3 + 2i

print(class(integer))
[1] "function"

Raw specifies values as raw bytes

# convert character to raw
raw_variable <- charToRaw("Welcome to Programiz")

print(raw_variable)
 [1] 57 65 6c 63 6f 6d 65 20 74 6f 20 50 72 6f 67 72 61 6d 69 7a
print(class(raw_variable))
[1] "raw"
# convert raw to character
char_variable <- rawToChar(raw_variable)

print(char_variable)
[1] "Welcome to Programiz"
print(class(char_variable))
[1] "character"