Loading...
Loading...

R Syntax and Basics

R has its own quirks and conventions. This tutorial covers the fundamental syntax rules that make R different from other programming languages.

1. Assignment Operators

R has two main assignment operators:

# Traditional arrow assignment
x <- 5  

# Equals sign (less common but works)
y = 10

Best Practice: Use <- for assignment to avoid confusion with function arguments.

Assignment Quiz

Which assignment operator is preferred in R?

  • <-
  • =
  • :=

2. Basic Operations

R handles math operations intuitively:

# Arithmetic
3 + 5 * 2  # Follows standard order of operations

# Exponentiation
2^3  # Returns 8, not 6 like some languages

# Integer division
7 %/% 2  # Returns 3

Operations Quiz

What does 7 %/% 2 return?

  • 3.5
  • 3
  • Error

3. Vectors - R's Workhorse

Vectors are fundamental in R. Create them with c():

# Numeric vector
numbers <- c(1, 2, 3, 4, 5)

# Character vector
fruits <- c("apple", "banana", "cherry")

# Sequence vector
sequence <- 1:5  # Same as c(1,2,3,4,5)

Vectors Quiz

How do you create a vector in R?

  • vector(1,2,3)
  • c(1,2,3)
  • [1,2,3]

4. Data Frames

The primary structure for datasets in R:

# Create a data frame
df <- data.frame(
  name = c("Alice", "Bob", "Charlie"),
  age = c(25, 30, 35),
  employed = c(TRUE, FALSE, TRUE)
)

# View first rows
head(df)

Data Frames Quiz

What function creates a data frame?

  • create.frame()
  • data.frame()
  • new_df()

5. Basic Functions

Creating and using functions in R:

# Define a function
calculate_mean <- function(x) {
  sum(x) / length(x)
}

# Use the function
calculate_mean(c(1, 2, 3))  # Returns 2

Functions Quiz

What's the correct way to define a function?

  • function calculate_mean(x) {}
  • calculate_mean <- function(x) {}
  • def calculate_mean(x):
0 Interaction
0 Views
Views
0 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home