Hello World

A sample R program is shown here.

greet <- function(name) {
  paste("Hello,", name, "!")
}

message <- greet("world")
print(message)
Strings
str_single <- "Hello"
str_multiline <- "Multiline\nstring"
toupper(str_multiline)

Useful string manipulation with stringr:

library(stringr)

name <- "John Doe"
str_to_lower(name)  # "john doe"
str_split(name, " ")  # List of "John" and "Doe"
Numbers
integer <- 42L
floating_point <- 3.14
complex_number <- complex(real = 2, imaginary = 3)

# Converting between types
float_to_int <- as.integer(3.7)  # 3

Working with vectors:

nums <- c(1, 2, 3, 4, 5)
mean(nums)  # 3
sum(nums)   # 15
Condition
day <- "sunday"

if (day %in% c("sunday", "saturday")) {
  print("Rest!")
} else if (day == "monday") {
  print("Groan!")
} else {
  print("Work!")
}

Using tryCatch for error handling:

result <- tryCatch({
  10 / 0
}, warning = function(w) {
  "Warning occurred!"
}, error = function(e) {
  "Error occurred!"
}, finally = {
  print("Cleanup complete.")
})

print(result)
Loops

For loop example:

for (i in 1:5) {
  print(paste("Iteration", i))
}

While loop example:

count <- 0
while (count < 5) {
  print(paste("Count is", count))
  count <- count + 1
}