Learn R with Real Code Examples
Updated Nov 21, 2025
Code Sample Descriptions
1
R Counter and Theme Toggle
count <- 0
isDark <- FALSE
updateUI <- function() {
cat(paste0('Counter: ', count, '\n'))
cat(paste0('Theme: ', ifelse(isDark, 'Dark', 'Light'), '\n'))
}
increment <- function() { count <<- count + 1; updateUI() }
decrement <- function() { count <<- count - 1; updateUI() }
reset <- function() { count <<- 0; updateUI() }
toggleTheme <- function() { isDark <<- !isDark; updateUI() }
# Simulate some actions
updateUI()
increment()
increment()
toggleTheme()
decrement()
reset()
Demonstrates a simple counter with theme toggling using R variables and console output.
2
R Random Number Generator
set.seed(123)
for (i in 1:3) {
num <- sample(1:100, 1)
cat(paste0('Random ', i, ': ', num, '\n'))
}
Generates random numbers between 1 and 100 and prints them.
3
R Todo List
todos <- c()
addTask <- function(task) { todos <<- c(todos, task); print(todos) }
removeTask <- function(index) { todos <<- todos[-index]; print(todos) }
# Simulate actions
addTask('Buy milk')
addTask('Write R code')
removeTask(1)
Maintains a simple todo list with add and remove functionality.
4
R Dice Roller
set.seed(42)
for (i in 1:3) {
roll <- sample(1:6, 1)
cat(paste0('Roll ', i, ': ', roll, '\n'))
}
Rolls a six-sided dice three times.
5
R Countdown Timer
count <- 5
while(count >= 0) {
cat(paste0('Countdown: ', count, '\n'))
count <- count - 1
}
cat('Done!\n')
Counts down from 5 to 0.
6
R Prime Checker
isPrime <- function(n) {
if(n < 2) return(FALSE)
for(i in 2:floor(sqrt(n))) {
if(n %% i == 0) return(FALSE)
}
return(TRUE)
}
nums <- c(7, 10, 13)
for(n in nums) {
cat(paste0(n, ' is ', ifelse(isPrime(n), 'Prime', 'Not Prime'), '\n'))
}
Checks if numbers are prime.
7
R Temperature Converter
cToF <- function(c) { c * 9/5 + 32 }
fToC <- function(f) { (f - 32) * 5/9 }
cat('25°C =', cToF(25), '°F\n')
cat('77°F =', fToC(77), '°C\n')
Converts Celsius to Fahrenheit and Fahrenheit to Celsius.
8
R Shopping Cart
cart <- data.frame(Item=character(), Price=numeric())
addItem <- function(item, price) { cart <<- rbind(cart, data.frame(Item=item, Price=price)); print(cart) }
removeItem <- function(index) { cart <<- cart[-index,]; print(cart) }
# Simulate actions
addItem('Apple', 2)
addItem('Banana', 3)
removeItem(1)
Adds and removes items in a shopping cart with total cost.
9
R Name Greeting
greet <- function(name) { cat(paste0('Hello, ', name, '! Welcome!\n')) }
# Simulate actions
greet('Saurav')
greet('Alice')
greet('Bob')
Greets users by name.
10
R Stopwatch
time <- 0
while(time < 5) {
cat(paste0('Stopwatch: ', time, ' seconds\n'))
time <- time + 1
}
cat('Done!\n')
Simulates a stopwatch incrementing seconds.