R Basics
Creating a R work environment on ParamGanga
Please create a virtual environment r_bec513 using the following command
# $ mamba create -n r_bec513 r-base=4.4 r-essentials
After this activate your environment and then install required packages as you need in the future. For
example, if you have to install the plotting package (ggplot2) for Project 4, first go to the R console by typing
R on the activated environment. And then type [Link]("ggplot2")
# $ mamba activate r_bec513
# (r_bed513)$ R
#R version 4.4.1 (2024-06-14) -- "Race for Your Life"
#Copyright (C) 2024 The R Foundation for Statistical Computing
#Platform: x86_64-conda-linux-gnu
#
#R is free software and comes with ABSOLUTELY NO WARRANTY.
#You are welcome to redistribute it under certain conditions.
#Type 'license()' or 'licence()' for distribution details.
#
# Natural language support but running in an English locale
#
#R is a collaborative project with many contributors.
#Type 'contributors()' for more information and
#'citation()' on how to cite R or R packages in publications.
#
#Type 'demo()' for some demos, 'help()' for on-line help, or
#'[Link]()' for an HTML browser interface to help.
#Type 'q()' to quit R.
#
#>[Link]("ggplot2")
Follow the prompt. I guess the Bengaluru server is option 42.
Different dataypes
Conceptually, they are same as you have learned in Python. For example, integers, float, string and more.
Go to the R console first.
# (r_bec513)$ R
Now run the following command to get basic understanding of R syntax.
x = 5
# To know the datatype of a variable, you can either use the function str
# (variable), or typeof (variable). See the examples below.
str(x)
## num 5
1
x = "5"
str(x)
## chr "5"
typeof(x)
## [1] "character"
# typecasting string to integer.
y = [Link](x)
print(y)
## [1] 5
str(y)
## int 5
# NOTE: please be careful and NOT use just `integer` function. See yourself
# what happens.
Important assignment operator
Most of the time you will see <- as an assignment operator in R. Both <- and = serve the same purpose. But
there is a subtle difference of allowed usages. For example, in function arguments, you can’t use <-. Lets
say you have a function square_of_a_number (num = 5), then you can’t say square_of_a_number (num
<- 5).
Usual addition, multiplication, division have same syntax. Try yourself.
R is great with numbers, but no so with strings
As any programming languages, R is great with numbers, meaning that it has a lot of functions to handle
statistics. But, you will have difficult time working with strings. See the example below. Coming from
Python background, it may seem very obvious that it should print H, but it doesn’t.
print("Hello World!")
## [1] "Hello World!"
s = "Hello World!"
print(s[1])
## [1] "Hello World!"
We will get to strings soon. Before that, lets look into some intermediate level data structures first.
Vectors
vec_of_numbers = c(1, 2, 1, 3, 2, 4, 5)
print(vec_of_numbers[1:3])
## [1] 1 2 1
So in the syntax above, we have learned a data structure equivalent to list in Python, but we don’t call it
list in R, because it is a dedicated structure in R that serves different purpose.
2
Thus, above we have a vector named vec_of_numbers. As we discussed in the class R is a 1-based indexing
language. So, things start from 1 and the last index is included. The output will be 1 2 1.
Named vectors
transcript_and_expression = c(T1 = 5, T2 = 20, T3 = 50, T4 = 10, T5 = 27)
print(transcript_and_expression)
## T1 T2 T3 T4 T5
## 5 20 50 10 27
# get names
print(names(transcript_and_expression))
## [1] "T1" "T2" "T3" "T4" "T5"
# get values
print(unname(transcript_and_expression))
## [1] 5 20 50 10 27
You may think that this is a dictionary with name and value mapping. But, it is not true. Try something
like the following
check_if_it_is_a_dict = c(x = c(5, 1, 3))
print(check_if_it_is_a_dict)
## x1 x2 x3
## 5 1 3
x just got expanded with three numeric suffixes to match the length of vector.
Mixed datatypes
R is also not that flexible to incorporte mixed datatypes in a vector as in Python we could do.
mixed_data_types = c(1, 2, 3, "4")
print(mixed_data_types)
## [1] "1" "2" "3" "4"
Everything becomes characters.
Indexing and slicing vectors
One natural operation working with vectors or other data strcutures holding multiple items is to undestand
indexing.
So let’s say we have a vector with 10 numbers.
first_10_numbers = seq(10)
To access value at a given index, you can simply say first_10_numbers[index]
first_10_numbers[5]
## [1] 5
But there are many questions in your mind:
1. How to get first five numbers from the vector?
3
2. How to get numbers 3 to 10 from the vector?
3. How to get all numbers except the first number in the vector?
4. How to get all numbers except the last number in the vector?
5. How to reverse the vector?
The fundamental understanding for the syntax is the following: inside the square bracket, it could either be a
number of a vector of numbers representing indices of interest. If you wish to not get the values at those
indices simply add a - sign before that.
So for question 1, all of the following will work:
print(first_10_numbers[seq(5)])
## [1] 1 2 3 4 5
print(first_10_numbers[1:5])
## [1] 1 2 3 4 5
print(first_10_numbers[c(1, 2, 3, 4, 5)])
## [1] 1 2 3 4 5
For question 3:
print(first_10_numbers[-c(1)])
## [1] 2 3 4 5 6 7 8 9 10
print(first_10_numbers[-1])
## [1] 2 3 4 5 6 7 8 9 10
You have to pay attention here is that -1 is not the index -1, rather it is saying exclude value at 1 and
keep others. The first line where I used c(1) best explain the process.
List
List in R you can think of it as dictionary in Python.
my_first_list = list()
my_first_list["single"] = "only single value"
my_first_list[[1]] = seq(10)
my_first_list[["1"]] = seq(11, 20)
my_first_list[["multiple"]] = rep("a", 5)
Please take a careful look at how keys and values are assigned. my_first_list["single"] has only one
square bracket, so it can only hold a single value be it integer or string or any data type. Try assigning a
vector.
my_first_list[[1]] has two brackets, stating that key 1 can hold a single value or vector or even a list.
my_first_list[["1"]] has two brackets, stating that key "1" (string type) can hold a single value or vector
or even a list. my_first_list[["multiple"]] : same as "1".
All these freedom you have. But, the best way to do is to have strings/characters as a key. To realize this,
just type the following:
names(my_first_list)
## [1] "single" "1" "multiple"
4
You will realize that the numeric key 1 has got no name. Although, you can access it by stating
my_first_list[[1]], other ways to access will be difficult, for example saying my_first_list$multiple.
Also, one way to know all the keys is to type my_first_list$ and press tab button multiple times.
This is it for now. Next document I will send by Monday describing dataframes and related operations.
In the meantime, you can also google a bit about dataframes and plotting using ggplot2 in R. One good
resource you would find here.