# This is a simple script that calculates the square of a number
number <- 5
square <- number^2
print(square) # Output the result[1] 25
File -> New File -> R Script. This opens a new script file where you can write and save your code.Ctrl + Enter (Windows) or Cmd + Enter (Mac).Ctrl + Shift + Enter.# This is a simple script that calculates the square of a number
number <- 5
square <- number^2
print(square) # Output the result[1] 25
File -> Save As and choosing a file name with the .R extension (e.g., my_script.R).# A for loop that prints numbers from 1 to 5
for (i in 1:5) {
print(i)
}[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
TRUE.# A while loop that prints numbers from 1 to 5
i <- 1
while (i <= 5) {
print(i)
i <- i + 1 # Increment the value of i
}[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
TRUE or FALSE.x <- 10
if (x > 5) {
print("x is greater than 5")
} else {
print("x is less than or equal to 5")
}[1] "x is greater than 5"
x <- 10
if (x > 15) {
print("x is greater than 15")
} else if (x > 5) {
print("x is greater than 5 but less than or equal to 15")
} else {
print("x is 5 or less")
}[1] "x is greater than 5 but less than or equal to 15"
function_name <- function(argument1, argument2, ...) {
# Code that performs some task
result <- argument1 + argument2 # Example operation
return(result) # Return the result
}# A function to calculate the square of a number
square <- function(x) {
return(x^2) # Return the square of the input
}square(4) # Call the function with input 4[1] 16
add_numbers <- function(a = 1, b = 2) {
return(a + b)
}
add_numbers(3, 5) # Call the function with specific values for a and b[1] 8