"Hello World!"
[1] "Hello World!"
'Hello World!'
[1] "Hello World!"
In this section, we will cover the following topics:
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
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
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
<- 10 + 2
math #print()
print(math)
[1] 12
# The = saves the caculation as math
= 10 + 2
math # print() will print out what is saved in the object math
print(math)
[1] 12
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:
<- TRUE
logical1 <- FALSE
logical2
# 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.
<- 5.5
height <- 1000
acres
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
<- "formula1"
motorsports
print(motorsports)
[1] "formula1"
print(class(motorsports))
[1] "character"
Integer specifies real values without decimal points
# the suffix i specifies its imaginary data.
<- 3 + 2i
complex
print(class(integer))
[1] "function"
Raw specifies values as raw bytes
# convert character to raw
<- charToRaw("Welcome to Programiz")
raw_variable
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
<- rawToChar(raw_variable)
char_variable
print(char_variable)
[1] "Welcome to Programiz"
print(class(char_variable))
[1] "character"
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 #: