# Example 1 using assignment operator "<-".
num_1 <- 1 # Assigning value 1 to variable num_1.
print(num_1) # Prints out what the variable num_1 contains.[1] 1
Mugabi Trevor .L
2024-09-02
Variables in R, Data types in R, Character data, Complex numbers, Logical data, Type conversion, aumeric data, Integer data, decimal data
In R: - A variable in R is used to store data that you want to work with. - You can assign a value to a variable using the assignment operator “<-” or “=”. - Once a variable is assigned a value, you can use the variable name to refer to that value in your code
# Example 1 using assignment operator "<-".
num_1 <- 1 # Assigning value 1 to variable num_1.
print(num_1) # Prints out what the variable num_1 contains.[1] 1
In the above code we see that now num_1 is assigned to the value of 1 therefore anywhere in our code we refer to “num_1” the 1 is whats being referenced.
# Example 2 using assignment operator "=".
num_2 = 3 # Assigning value of 3 to variable num_2.
print(num_2) # Prints out what the variable num_1 contains.[1] 3
In the above code we see that now num_2 is assigned to the value of 3. Therefore anywhere in our code we refer to “num_2” the 3 is whats being referenced. With this knowledge in mind so if num_1 is 1 and num_2 is 3 then num_1 plus num_3 should equal to 1 + 3 which equals to 4 . Lets test this out below and see what we end up with.
# Testing above theory that num_1 + num_2 = 4 since num_1 = 1 and num_2 = 3.
# Adding num1 and num_2 putting the outcome of the operation into a variable called results.
results <- num_1 + num_2
print(results) # printing out the results.[1] 4
Look at that we get a Four as the answer, this proves the concept of variables being containers for whatever we may like to store. Which brings us to the Question of “What Exactly can we store in a variable 🤔🤔?”.
When working with R, understanding different data types is crucial. These types determine how R handles and processes your data. So, let’s break it down
Numeric data in R refers to any data that represents numbers. This can include integers (whole numbers) and doubles (floating-point numbers or decimals).
Numeric data is used for mathematical operations like addition, subtraction, multiplication, and division.
Character data in R consists of text or strings. Strings are sequences of characters enclosed in either single or double quotes.
Character data is often used for storing names, addresses, labels, or any other non-numeric information.
Factor data is used to represent categorical data, where the data can take on a limited number of distinct values or levels.
Factors are useful for storing data that has a specific number of categories or a natural order to them, such as “Yes” and “No” or “Low”, “Medium”, and “High”.
Factors are especially useful in statistical modeling and data analysis. To convert a data type to a factor we use the Factor() function as shown below
Logical values in R represent TRUE or FALSE (often used in conditional statements and comparisons).
Logical values are essential for control flow in programs, allowing you to execute different code depending on conditions.
Integers are whole numbers that do not have a fractional or decimal part. In R, integers are represented by the data type integer.
You can explicitly define an integer by appending an L to the number. By default, R treats numbers without a decimal as numeric (which are doubles), so adding the L ensures it is stored as an integer.
You can perform standard arithmetic operations with integers, just as you would with numeric data.
Complex numbers consist of a real part and an imaginary part. In R, complex numbers are represented using the complex data type.
The imaginary unit is represented by i, and you can create a complex number by combining a real and an imaginary part.See code below
Complex numbers support various operations like addition, subtraction, multiplication, and division. R also provides functions to extract the real Re() and imaginary Im() parts of a complex number.
Type conversion (or casting) is the process of converting one data type to another. In R, you might need to convert data types for various reasons, such as converting characters to numeric data for calculations or converting numbers to factors for categorical analysis.
Inorder to type convert we use the as.type function.But before you know how to type cast we need to find out how to find out the current data type and we using a function know as class() function to check for that.
To convert a Numeric to Character we call the as.character() function on the variable or Data type we are interested into converting.
NB: Converisons work where the conversion makes sense thats to say i can convert a numeric number 5 into a character “5”. I could still convert the character “5” back into a Numeric number 5. But you can convert a character such as “a” into a Numeric.
See code below.
##### Converting Numeric to Character. #####
num <- 123 # start value.
# Checking the type before conversion.
print(paste("Type before conversion:", class(num)))
# Converting type and saving it into variable num_char.
num_char <- as.character(num)
# Checking the type after conversion.
print(paste("Type after conversion:", class(num_char)))
# Printing out the converted start value.
print(num_char) # Outputs "123"[1] "Type before conversion: numeric"
[1] "Type after conversion: character"
[1] "123"
To convert a character into a Numeric we use the as.Numeric() function on the Variable we want to convert, see code below.
##### Character to Numeric #####.
char <- "456" # start value.
# Checking the type before conversion.
print(paste("Type before conversion:", class(char)))
# Converting type and saving it into variable char_num.
char_num <- as.numeric(char)
# Checking the type after conversion.
print(paste("Type after conversion:", class(char_num)))
# Printing out the converted start value.
print(char_num) # Outputs 456[1] "Type before conversion: character"
[1] "Type after conversion: numeric"
[1] 456
To convert from a Numeric to a Factor we use the as.Factor() function.
###### Numeric to Factor #####
grades <- c(85, 90, 75) # start value.
# Checking the type before conversion.
print(paste("Type after conversion:", class(grades)))
# Converting type and saving it into variable grades_factor.
grades_factor <- as.factor(grades)
# Checking the type after conversion.
print(paste("Type after conversion:", class(grades_factor)))
# Printing out the converted start value.
print(grades_factor) # Outputs a factor with levels 75, 85, 90[1] "Type after conversion: numeric"
[1] "Type after conversion: factor"
[1] 85 90 75
Levels: 75 85 90
HINT: - If by now you have not caught on ! Let me help out. Generally to convert a specify data type to another we call the as.type function but the idea is you write the ‘as.”then here you write the datatype you wish to convert to”()’. - So thats to say if am to convert to Numeric i will call as.Numeric(), to integer i will call as.integer(), to complex i will call as.complex(). i think you see the pattern here. Happy R wizarding.
This section holds some practice questions about all the above covered concepts, give it a try and see how it goes.
Create two numeric variables, a and b, and assign them any numbers you like.
Perform the following operations and print the results:
Sum of a and b.
Difference between a and b.
Product of a and b.
Division of a by b.
Create two character variables, first_name and last_name, and assign them your first and last names.
Concatenate first_name and last_name into a single string with a space between them, and print the result.
Create a factor variable days representing the days of the week, with at least three repeated days.
Print the levels of the days factor.
Count the number of occurrences of each day and print the result.
Create a numeric variable score and assign it a value.
Convert score to a character and print the result.
Create a character variable age_str that contains a number as a string (e.g., “25”).
Convert age_str to a numeric value and print the result.
Create a factor from a vector of numbers representing exam scores. Print the factor levels.
Create a logical variable is_holiday and assign it a value (TRUE or FALSE).
Write an if statement that prints “Relax, it’s a holiday!” if is_holiday is TRUE, and “Time to work!” if is_holiday is FALSE.
Compare two numbers using the greater than (>) operator and store the result in a logical variable. Print the result.