Skip to main content

5 Fundamentals: Syntax, Operators, and Workspace Management

 

"R fundamentals, R syntax, R operators, R vectors, workspace management, data analysis

Mastering R’s syntax and core operators sets the foundation for advanced data analysis. In this post, you’ll learn how to assign variables, work with vectors, explore logical operations, and manage your R workspace effectively. By the end, you’ll understand the building blocks that power every script, function, and package you’ll use on your R journey.

1. Basic Arithmetic and Assignment

Every calculation in R relies on a handful of arithmetic operators and a clear way to store results.

  1. Arithmetic operators

    • + addition

    • - subtraction

    • * multiplication

    • / division

    • ^ exponentiation

r
# Simple calculations
3 + 5       # 8
10 * 2      # 20
(4 - 1) / 3 # 1
2^3         # 8
  1. Assignment operators

    • <- is the idiomatic arrow for assigning a value to a variable

    • = works similarly in most contexts, though <- is preferred in scripts

r
# Variable assignment
x <- 42
y = x * 2

# Inspect values
x    # 42
y    # 84

Adopting a consistent assignment style makes your code easier to read and review. Save complex expressions to intermediate variables to improve clarity:

r
mean_value <- (3 + 5 + 7) / 3

2. Working with Vectors

Vectors are one-dimensional collections of elements of the same type. They underpin nearly every data structure in R.

  1. Creating vectors

    • Use c() to combine values into a vector

    • Generate sequences with : or seq()

r
numeric_vec <- c(1, 2, 3, 4, 5)
char_vec    <- c("apple", "banana", "cherry")
seq_vec     <- seq(from = 0, to = 1, by = 0.2)
  1. Indexing and subsetting

    • Access elements by position ([ ])

    • Use logical vectors to filter values

r
numeric_vec[2]          # 2
numeric_vec[c(1, 3, 5)] # 1 3 5

# Filter values greater than 3
numeric_vec[numeric_vec > 3]  # 4 5
  1. Vectorized operations

    • Apply arithmetic and functions element-wise

    • Recycling rules repeat shorter vectors

r
a <- c(10, 20, 30)
b <- c(1, 2)
a + b   # 11 22 31 (2 recycled)
log(a)  # natural log of each element

Mastering vectors lets you avoid explicit loops for many tasks, leading to cleaner and faster code.

3. Logical Operators

Logical operators allow you to compare values and control the flow of your analysis.

  1. Comparison operators

    • > greater than

    • < less than

    • == equal to

    • != not equal to

    • >= greater than or equal to

    • <= less than or equal to

r
5 > 3        # TRUE
2 == 2       # TRUE
4 != 4       # FALSE
  1. Logical connectors

    • & element-wise AND

    • | element-wise OR

    • && short-circuit AND (first element only)

    • || short-circuit OR (first element only)

r
# Element-wise logical
c(TRUE, FALSE, TRUE) & c(TRUE, TRUE, FALSE)  # TRUE FALSE FALSE

# Short-circuit logical (useful in control flow)
if (length(numeric_vec) > 0 && mean(numeric_vec) > 3) {
  print("Vector has values and mean exceeds 3")
}

Use logical operators to build filters, conditionals, and more robust data pipelines.

4. Workspace Management

A tidy workspace prevents confusion and ensures scripts run reliably each time.

  1. Listing objects

    • ls() shows all variables and functions in memory

    • ls(pattern = "df") filters by name

r
ls()               # lists x, y, numeric_vec, char_vec, etc.
ls(pattern = "vec")# lists numeric_vec, char_vec, seq_vec
  1. Removing objects

    • rm() deletes specified variables

    • rm(list = ls()) clears the entire workspace

r
rm(y)              # removes y only
rm(list = ls())    # start fresh
  1. Saving and loading sessions

    • save.image("workspace.RData") saves everything in your workspace

    • load("workspace.RData") restores saved objects

r
# Save current state
save.image("my_analysis.RData")

# Later or in a new session
load("my_analysis.RData")

Regularly clearing and saving your workspace avoids unintended side effects when rerunning scripts and makes your analyses reproducible.

Conclusion and Next Steps

In this post, you’ve mastered R’s basic arithmetic, assignment operators, vector operations, logical comparisons, and workspace management tools. These fundamentals are the bedrock of every data manipulation and modeling task you’ll undertake in R.

Next up, we’ll dive into Data Structures—exploring matrices, lists, data frames, and tibbles, and learning how to choose the right structure for your data. If you have questions about assignments, vector quirks, or workspace tips, leave a comment below. Your feedback guides our journey, and I’ll address common pain points in upcoming posts. Happy coding!

Comments

Popular posts from this blog

Alfred Marshall – The Father of Modern Microeconomics

  Welcome back to the blog! Today we explore the life and legacy of Alfred Marshall (1842–1924) , the British economist who laid the foundations of modern microeconomics . His landmark book, Principles of Economics (1890), introduced core concepts like supply and demand , elasticity , and market equilibrium — ideas that continue to shape how we understand economics today. Who Was Alfred Marshall? Alfred Marshall was a professor at the University of Cambridge and a key figure in the development of neoclassical economics . He believed economics should be rigorous, mathematical, and practical , focusing on real-world issues like prices, wages, and consumer behavior. Marshall also emphasized that economics is ultimately about improving human well-being. Key Contributions 1. Supply and Demand Analysis Marshall was the first to clearly present supply and demand as intersecting curves on a graph. He showed how prices are determined by both what consumers are willing to pay (dem...

Fundamental Analysis Case Study NVIDIA

  Executive summary NVIDIA is analyzed here using the full fundamental framework: balance sheet, income statement, cash flow statement, valuation multiples, sector comparison, sensitivity scenarios, and investment checklist. The company shows exceptional profitability, strong cash generation, conservative liquidity and net cash, and premium valuation multiples justified only if high growth and margin profiles persist. Key investment considerations are growth sustainability in data center and AI, margin durability, geopolitical and supply risks, and valuation sensitivity to execution. The detailed numerical work below uses the exact metrics you provided. Company profile and market context Business model and market position Company NVIDIA Corporation, leader in GPUs, AI accelerators, and related software platforms. Core revenue streams : data center GPUs and systems, gaming GPUs, professional visualization, automotive, software and services. Strategic advantage : GPU architecture, C...

Behavioral Portfolio Theory (BPT) – Rethinking Investor Behavior and Portfolio Construction

  Traditional finance theories like Modern Portfolio Theory (MPT) assume that investors are perfectly rational and risk-averse, aiming to maximize utility by optimizing expected returns and variance. However, decades of research in behavioral finance have shown that investors often deviate from purely rational behavior. Behavioral Portfolio Theory (BPT) , introduced by Shefrin and Statman in 2000, offers a fresh perspective by integrating psychological and emotional factors into portfolio construction. What is Behavioral Portfolio Theory? Behavioral Portfolio Theory suggests that investors mentally segment their wealth into multiple “mental accounts” or layers, each with distinct goals, risk preferences, and expectations. Unlike MPT's single-layer approach focusing on an overall risk-return tradeoff, BPT models the portfolio as a layered pyramid , where each layer reflects different investor aspirations. For example: The bottom layer prioritizes capital preservation and safe...