# Day 27 : 'R' Programming

**Meta Description:** A beginner friendly introduction to R programming for data science. Learn R syntax, data types, vectors, data frames, and operators with simple examples and expected outputs.

## Introduction

Picture a school teacher who has just received the exam marks of 500 students and wants quick answers: What is the average? What is the highest score? How are the marks spread out?

With a general purpose tool, she would write a few lines to load the data, import a library, and compute each number one by one. Now imagine instead a tool built by statisticians, for statisticians, where a single word, `summary(marks)`, instantly prints the minimum, maximum, median, mean, and quartiles of all 500 marks.

That is the feeling of working in **R**. If Python is a Swiss army knife that can do almost anything, R is a **precision lab instrument** designed specifically for analyzing data, running statistical tests, and drawing publication quality charts. Statistics is not an add-on in R, it is the foundation of the language.

Since we spent the last few days in the Big Data world (Hadoop, Spark, NoSQL), today we add a new tool to the toolbox. In the coming days, R will let us handle data, visualize it, and run statistical analysis, all of which feed into our Day 30 case study.

## Theory

> **In one line:** R is a free, open source programming language and environment built for statistical computing, data analysis, and visualization.

### A Brief History

R’s story starts at **Bell Labs**, where John Chambers and colleagues created a language called **S** in 1976 for statistical analysis. S was powerful but commercial. In 1993, two professors at the University of Auckland, **Ross Ihaka and Robert Gentleman**, created a free implementation inspired by S and named it **R**, partly after the first letters of their own first names and partly as a playful nod to S. In 1997, **CRAN** (the Comprehensive R Archive Network) was launched as the central place to share R packages, and today it hosts a huge number of packages covering almost every statistical technique imaginable. The popular editor **RStudio** (now called Posit) arrived in 2011 and made R far friendlier to use.

### Why People Choose R

*   Built for statistics, with hypothesis tests, regression, and modeling available out of the box
    
*   Excellent visualization through packages like **ggplot2** (Day 28)
    
*   Data frames are a core part of the language, not an add-on
    
*   Huge community and package ecosystem on CRAN
    
*   Strongly used in academia, healthcare, finance, and research
    

## R vs Python at a Glance

![](https://cdn.hashnode.com/uploads/covers/632da7dc3a049a0d9db73ba7/37708dd4-2824-408e-a163-e19368be6a9b.png align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Interviewers love the indexing difference. In R, the first element of a vector is <code>x[1]</code>. In Python, it is <code>x[0]</code>. Mixing these up is one of the most common beginner mistakes.</div>
</div>

### Core Syntax Rules

*   R is **case sensitive**, so `Data` and `data` are different names
    
*   The preferred assignment operator is `<-` (an arrow pointing at the variable)
    
*   Comments start with `#`
    
*   No need to declare variable types, R decides automatically (dynamic typing)
    
*   Almost everything in R is a **vector**, even a single number is a vector of length 1
    

## Basic Data Types

![](https://cdn.hashnode.com/uploads/covers/632da7dc3a049a0d9db73ba7/5228d896-ea1f-4727-bf75-d08b5d9b0d06.png align="center")

### Core Data Structures

*   **Vector**: a sequence of values of the same type
    
*   **List**: a collection that can hold different types together
    
*   **Matrix**: a 2D grid of values of the same type
    
*   **Factor**: categorical data with a fixed set of levels
    
*   **Data frame**: a table where each column can have a different type (the star of R)
    

### Operators

*   **Arithmetic:** `+ - * / ^ %%` (modulus) `%/%` (integer division)
    
*   **Relational:** `== != > < >= <=`
    
*   **Logical:** `&` (and), `|` (or), `!` (not)
    
*   **Assignment:** `<-`, `=`, `->`
    
*   **Special:** `%in%` (membership), `:` (sequence)
    

## Practical

R does not run in your Python Jupyter kernel by default. You have a few easy ways to follow along without a heavy setup:

Posit Cloud (free tier): a browser based RStudio, no installation Google Colab with an R runtime: a Colab notebook that runs R instead of Python Local install: R plus RStudio, or the R kernel for Jupyter (IRkernel), if you prefer your usual notebook

Each block below is one cell. The expected output is shown beneath each, so you can compare with your own screenshots.

Cell 1: Your first R code

```python
print("Hello, R!") 
2 + 3
```

`[1] "Hello, R!"`

`[1] 5`

The \[1\] simply tells you the index of the first item printed on that line.

Cell 2: Variables and assignment

```python
x <- 10 
y <- 3 
name <- "Asha" 
x 
name
```

`[1] 10`

`[1] "Asha"`

Cell 3: Arithmetic operators

```python
x + y 
x - y 
x * y 
x / y 
x ^ y 
x %% y 
x %/% y
```

`[1] 13`

`[1] 7`

`[1] 30`

`[1] 3.333333`

`[1] 1000`

`[1] 1`

`[1] 3`

%% gives the remainder (10 divided by 3 leaves 1), and %/% gives the whole number part of the division (3).

Cell 4: Checking data types

```python
class(42) class(42L) class("hello") class(TRUE) class(3+2i)
```

`[1] "numeric"`

`[1] "integer"`

`[1] "character"`

`[1] "logical"`

`[1] "complex"`

Notice 42 is numeric but 42L is integer. The L suffix is what makes the difference.

Cell 5: Creating vectors

```python
scores <- c(85, 92, 78, 90, 66) 
length(scores) 
sum(scores) 
mean(scores) 
max(scores) 
min(scores)
```

`[1] 5`

`[1] 411`

`[1] 82.2`

`[1] 92`

`[1] 66`

c() stands for “combine” and is the main way to build a vector.

Cell 6: Summary statistics in one line

```python
summary(scores)
```

```python
Min. 1st Qu. Median Mean 3rd Qu. Max. 

66.0  78.0   85.0  82.2  90.0   92.0
```

This is the “one word, full answer” feeling from our teacher example.

Cell 7: Vectorized operations

```python
scores + 5 
scores * 2 
scores > 80 
scores[scores > 80]
```

`[1] 90 97 83 95 71`

`[1] 170 184 156 180 132`

`[1] TRUE TRUE FALSE TRUE FALSE`

`[1] 85 92 90`

No loop needed. R applies the operation to every element at once, which is called vectorization. The last line filters the vector using a logical condition.

Cell 8: Indexing (remember, it starts at 1)

```python
scores[1] 
scores[c(1, 3)] 
scores[-1]
```

`[1] 85`

`[1] 85 78`

`[1] 92 78 90 66`

A negative index means “everything except this position.”

Cell 9: Sequences and repetition

```python
1:5 
seq(0, 20, by = 5) 
rep("R", 3)
```

`[1] 1 2 3 4 5`

`[1] 0 5 10 15 20`

`[1] "R" "R" "R"`

Cell 10: Relational and logical operators

```python
5 == 5 
5 != 3 
a <- TRUE 
b <- FALSE 
a & b 
a | b 
!a 
7 %in% c(1, 7, 9)
```

`[1] TRUE`

`[1] TRUE`

`[1] FALSE`

`[1] TRUE`

`[1] FALSE`

`[1] TRUE`

Cell 11: Lists, matrices, and factors

```python
student <- list(name = "Asha", age = 21, marks = c(80, 90, 85)) student$name 
student$marks[2]

m <- matrix(1:6, nrow = 2, ncol = 3) 
m 
dim(m)

gender <- factor(c("M", "F", "F", "M", "F")) 
gender 
table(gender)
```

```python
[1] "Asha"
[1] 90

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[1] 2 3

[1] M F F M F
Levels: F M
gender
F M 
3 2
```

A list holds mixed types, a matrix fills column by column by default, and a factor stores categories with defined levels.

Cell 12: Data frames (the most important structure)

```python
df <- data.frame( Name = c("Asha", "Ravi", "Meera"), Age = c(21, 23, 22), Marks = c(88, 75, 92) ) 
df 
str(df) 
mean(df$Marks) 
df[df$Marks > 80, ]
```

```python
   Name Age Marks
1  Asha  21    88
2  Ravi  23    75
3 Meera  22    92

'data.frame':	3 obs. of  3 variables:
 $ Name : chr  "Asha" "Ravi" "Meera"
 $ Age  : num  21 23 22
 $ Marks: num  88 75 92

[1] 85

   Name Age Marks
1  Asha  21    88
3 Meera  22    92
```

$ picks a column, and df\[condition, \] filters rows (the empty space after the comma means “all columns”). We will explore this much deeper tomorrow with dplyr.

Cell 13: Conditions and functions

```python
marks <- 72 
if (marks >= 90) { print("Grade A") } 
else if (marks >= 70) { print("Grade B") } 
else { print("Grade C") }

square <- function(n) { return(n^2) } 
square(7) 
```

`[1] "Grade B"`

`[1] 49`

Key Takeaways

*   R is a free, open source language built for statistics, analysis, and visualization
    
*   Use <- for assignment, and remember that R is case sensitive Indexing starts at 1 in R (it starts at 0 in Python)
    
*   Basic types: numeric, integer, character, logical, complex
    
*   Core structures: vector, list, matrix, factor, data frame
    
*   Operations are vectorized, so you rarely need loops
    
*   %% is remainder, %/% is integer division, %in% checks membership
    
*   Data frames are the workhorse of data analysis in R, and we build on them in the next two days
    

## Interview Questions to Look Out For

1.  What is R and why is it popular in data science? R is an open source programming language designed for statistical computing, data analysis, and visualization. It is popular because of its rich statistical capabilities, its huge package ecosystem on CRAN, and strong visualization tools like ggplot2.
    
2.  What are the main differences between R and Python? R was built mainly for statistics and data analysis, while Python is a general purpose language with strong machine learning and deployment support. R indexing starts at 1 and Python at 0, R uses <- commonly for assignment, and R has data frames built in whereas Python uses the Pandas library.
    
3.  What is the difference between <- and = for assignment in R? Both can assign values at the top level, but <- is the convention and works everywhere. The = operator is mainly used to pass arguments inside function calls, and using <- there would behave differently, so keeping <- for assignment avoids confusion.
    
4.  What are the basic data types in R? The basic (atomic) types are numeric, integer, character, logical, and complex. You can check any object’s type with class() or typeof().
    
5.  What is a vector in R, and what happens if you mix data types inside one? A vector is a sequence of elements of the same type. If you mix types, R silently converts everything to the most flexible type through coercion. For example, c(1, "a", TRUE) becomes the character vector "1" "a" "TRUE".
    
6.  What is the difference between a vector and a list? A vector holds elements of a single type, while a list can hold elements of different types and even different structures, such as numbers, text, vectors, or other lists, all together.
    
7.  What is the difference between a matrix and a data frame? A matrix is a 2D structure where every element must be the same type. A data frame is also 2D, but each column can have its own type, which makes it suitable for real world tabular data with numbers, text, and categories mixed together.
    
8.  What is a factor in R and why is it useful? A factor represents categorical data by storing a set of fixed levels. It is useful for statistical modeling and plotting, because R treats the values as categories rather than plain text, and it stores them efficiently.
    
9.  What is vectorization and the recycling rule in R? Vectorization means an operation is applied to every element of a vector at once without an explicit loop. Recycling means that when two vectors of different lengths are combined, the shorter one is repeated to match the longer one. For example, c(1,2,3,4) + c(10,20) gives 11 22 13 24. If the longer length is not a multiple of the shorter one, R gives a warning.
    
10.  What is the difference between NA, NULL, and NaN in R? NA represents a missing value within data. NULL represents the absence of an object altogether, such as an empty result. NaN means “Not a Number” and appears from undefined math such as 0/0. Notably, is.na() returns TRUE for both NA and NaN.
     

## Conclusion

Today we introduced R as a language built by statisticians for analyzing data, tracing its roots from the S language at Bell Labs to the modern CRAN ecosystem. We covered R’s syntax rules, its basic data types, its core data structures (vectors, lists, matrices, factors, and data frames), and its operators, and saw how vectorization lets us avoid loops. With these fundamentals in place, we are ready to start manipulating and visualizing real data in R tomorrow.

Next up: Day 28: Data Handling & Visualization in R (dplyr, ggplot2)
