Learning R Syntax

Understanding the fundamentals of R programming

Variables and Data Types

In R, you can create variables to store data. R has several built-in data types, including numeric, character, logical, and more.


const > x <- 10
const > y <- "hello"
const > z <- TRUE
                        

Conditional Statements

You can use conditional statements like if-else to make decisions in R based on certain conditions.


const > x <- 10
const > if (x > 5) print("greater than 5") else
print("less than or equal to 5")
                        

Loops

You can use loops like for and while to repeat a block of code multiple times.


const > for (i in 1:5) print(i)
                        

Function Definitions

You can define your own functions in R to encapsulate a block of code for reuse.


const > square <- function(x) return(x^2)
const > print(square(3))
                        

Practice Exercises

Now that you've learned the basics of R syntax, it's time to practice. Try the following exercises to test your understanding:

  1. Create a variable called "age" and assign your age to it.
  2. Write an if-else statement to check if the variable "age" is greater than 18.
  3. Use a for loop to print the numbers from 1 to 10.
  4. Define a function called "double" that takes a number as input and returns the double of that number.