R syntax is straightforward and easy to learn. Below are some fundamental concepts to help you write R code correctly.
Use the #
symbol to add comments in your R code. Comments are ignored when the code runs.
# This is a comment in R print("Hello, world!") # This prints a message
Assign values to variables using the arrow operator <-
or the equals sign =
. The arrow is preferred in R.
x <- 5 # Assign 5 to x y = 10 # Also valid, but less common print(x + y) # Output: 15
R has several basic data types:
numeric
— numbers (e.g., 5, 3.14)character
— text strings (e.g., "Hello")logical
— TRUE or FALSE valuesinteger
— whole numbers (e.g., 1L, 10L)Basic arithmetic operators in R include:
+
Addition-
Subtraction*
Multiplication/
Division^
Exponentiation (power)%%
Modulus (remainder)# Variables and arithmetic a <- 7 b <- 3 sum <- a + b diff <- a - b prod <- a * b quot <- a / b power <- a ^ b mod <- a %% b print(sum) # 10 print(diff) # 4 print(prod) # 21 print(quot) # 2.333333 print(power) # 343 print(mod) # 1
;
.Var
and var
are different.print()
to output results.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!