Here are some basic R syntax examples that you can use to get started:
1. Assigning values to variables:
x <- 5 # Assign the value 5 to the variable x y <- "hello" # Assign the string "hello" to the variable y
2. Basic arithmetic operations:
a <- 5 b <- 3 c <- a + b # Addition d <- a - b # Subtraction e <- a * b # Multiplication f <- a / b # Division g <- a ^ b # Exponentiation h <- a %% b # Modulo (remainder)
3. Data structures:
# Vectors: vec <- c(1, 2, 3, 4, 5) # Create a numeric vector vec2 <- c("red", "green", "blue") # Create a character vector # Matrices: mat <- matrix(c(1, 2, 3, 4, 5, 6), nrow=2, ncol=3) # Create a 2x3 matrix # Data frames: df <- data.frame(name=c("Alice", "Bob", "Charlie"), age=c(25, 30, 35)) # Create a data frame with two columns
4. Functions:
# Built-in functions: sqrt(25) # Square root of 25 length(vec) # Length of vector vec mean(vec) # Mean of vector vec sd(vec) # Standard deviation of vector vec # User-defined functions: my_func <- function(x, y) { z <- x + y return(z) } result <- my_func(3, 4) # Call the function with arguments 3 and 4
5. Control structures:
# If-else statement: x <- 5 if (x > 0) { print("x is positive") } else { print("x is negative or zero") } # For loop: for (i in 1:5) { print(i) } # While loop: i <- 1 while (i <= 5) { print(i) i <- i + 1 }
These are just a few examples of the basic syntax in R. As you continue to work with R, you will learn more advanced features and techniques for data analysis and visualization.