📘 Introduction to R Programming – Basics with Examples
📌 1. Basic Syntax
- Case sensitive.
- Comments start with
#
# This is a comment
print("Hello, R!")
🔢 2. Operators
🔸 Arithmetic
2 + 3 # 5
4 * 5 # 20
6 %% 4 # 2
5 ^ 2 # 25
🔸 Relational
4 == 4 # TRUE
5 != 3 # TRUE
3 < 2 # FALSE
🔸 Logical
TRUE & FALSE # FALSE
TRUE | FALSE # TRUE
!TRUE # FALSE
🔤 3. Data Types
- Numeric:
x <- 45.5
- Integer:
x <- 100L
- Character:
x <- "Hello"
- Logical:
x <- TRUE
x <- 42
print(class(x)) # "numeric"
📦 4. Variable Declaration
name <- "R Language"
age <- 25
_height <- 170
🔐 5. Constants
Use uppercase by convention. R doesn't enforce constant rules.
PI <- 3.14159
MAX_USERS <- 100
📥 6. Input
name <- readline("Enter your name: ")
num <- as.numeric(readline("Enter a number: "))
📤 7. Output
x <- 10
print(x)
cat("Value is", x)
✅ Solved Examples
Example 1: Add Two Numbers
a <- as.numeric(readline("Enter first number: "))
b <- as.numeric(readline("Enter second number: "))
sum <- a + b
cat("Sum is", sum)
Example 2: Check Even or Odd
num <- as.integer(readline("Enter a number: "))
if (num %% 2 == 0) {
print("Even")
} else {
print("Odd")
}
❓ Unsolved Practice
- Swap two numbers without using a third variable.
- Calculate the square root of a number.
- Compare two numbers and print the greater one.
- Take name and age input, then display a greeting.
- Calculate area of circle using radius and constant PI.
0 Comments