19 Sep Top 30 Trending R Coding Examples
- R Free Notes: https://studyopedia.com/tutorials/r-tutorial/
1. Write a function to reverse a character string in R
Code:
reverse_string <- function(s) {
split_str <- strsplit(s, "")[[1]]
paste(rev(split_str), collapse = "")
}
print(reverse_string("RProgramming"))
Output:
[1] "gnimmargorPR"
Explanation: strsplit breaks the string into individual character vectors, rev reverses vector elements, and paste reconstitutes the string.
2. Filter rows in a data frame using base R logical indexing
Code:
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 32, 28)
)
filtered <- df[df$age > 26, ]
print(filtered)
Output:
name age 2 Bob 32 3 Charlie 28
Explanation: df$age > 26 creates a boolean vector, extracting only rows where the age expression evaluates to TRUE.
3. Filter data rows using tidyverse dplyr::filter() in R Programming
Code:
suppressPackageStartupMessages(library(dplyr))
df <- data.frame(
score = c(88, 92, 75, 95),
status = c("pass", "pass", "fail", "pass")
)
result <- df %>% filter(score >= 90)
print(result)
Output:
score status 1 92 pass 2 95 pass
Explanation: dplyr’s filter function isolates rows meeting condition criteria, using pipe operators (%>%) for clean readability.
4. Create a new computed column using dplyr::mutate() in R Programming
Code:
library(dplyr) df <- data.frame(price = c(100, 200, 300)) df <- df %>% mutate(tax = price * 0.1, total = price + tax) print(df)
Output:
price tax total 1 100 10 110 2 200 20 220 3 300 30 330
Explanation: mutate adds new variable columns or modifies existing variables in place inside data frames.
5. Calculate group summary statistics using group_by and summarize in dplyr in R Programming
Code:
library(dplyr)
df <- data.frame(
category = c("A", "A", "B", "B"),
val = c(10, 20, 30, 40)
)
summary_df <- df %>%
group_by(category) %>%
summarize(mean_val = mean(val), count = n())
print(summary_df)
Output:
# A tibble: 2 × 3 category mean_val count <chr> <dbl> <int> 1 A 15 2 2 B 35 2
Explanation: group_by partitions records by specified categorical factors, allowing summarize to compute aggregated metrics per group.
6. Convert wide format data frame into long format using tidyr::pivot_longer() in R Programming
Code:
library(tidyr) wide_df <- data.frame( id = 1:2, q1 = c(10, 20), q2 = c(30, 40) ) long_df <- wide_df %>% pivot_longer(cols = c(q1, q2), names_to = "quarter", values_to = "sales") print(long_df)
Output:
# A tibble: 4 × 3
id quarter sales
<int> <chr> <dbl>
1 1 q1 10
2 1 q2 30
3 2 q1 20
4 2 q2 40
Explanation: pivot_longer reshapes datasets from wide to long formats by gathering specified columns into key-value pairs.
7. Fit a linear regression model using lm() in R Programming
Code:
x <- c(1, 2, 3, 4, 5) y <- c(2, 4, 5, 4, 5) model <- lm(y ~ x) print(coef(model))
Output:
(Intercept) x
2.2 0.6
Explanation: lm fits linear models, mapping dependent variable y onto independent predictor x, and coef extracts model intercept and slopes.
8. Apply a function to list elements using lapply() in R Programming
Code:
numbers <- list(a = 1:3, b = 4:6) squared <- lapply(numbers, function(x) x^2) print(squared)
Output:
$a [1] 1 4 9 $b [1] 16 25 36
Explanation: lapply traverses lists or vector objects, applying a custom or built-in function to each element and returning a list.
9. Apply a function and return a simplified vector using sapply() in R Programming
Code:
vec <- list(c(1, 2, 3), c(10, 20)) means <- sapply(vec, mean) print(means)
Output:
[1] 2 15
Explanation: sapply wraps lapply operations, automatically simplifying output list structures into atomic vectors or matrices when possible.
10. Check for missing values (NA) and handle them in R Programming
Code:
vals <- c(10, NA, 30, NA, 50) print(is.na(vals)) clean_mean <- mean(vals, na.rm = TRUE) print(clean_mean)
Output:
[1] FALSE TRUE FALSE TRUE FALSE [1] 30
Explanation: is.na returns logical indicators for missing observations; passing na.rm = TRUE instructs statistical functions to ignore NA entries.
11. Replace missing values using tidyr::replace_na() in R Programming
Code:
library(tidyr) df <- data.frame(v = c(1, NA, 3)) df_clean <- df %>% replace_na(list(v = 0)) print(df_clean)
Output:
v 1 1 2 0 3 3
Explanation: replace_na takes target column names mapping replacement default values for missing data values.
12. Perform an inner join between two data frames using dplyr::inner_join() in R Programming
Code:
library(dplyr)
df1 <- data.frame(id = c(1, 2), name = c("A", "B"))
df2 <- data.frame(id = c(1, 2), score = c(90, 85))
joined <- inner_join(df1, df2, by = "id")
print(joined)
Output:
id name score 1 1 A 90 2 2 B 85
Explanation: inner_join merges rows from two datasets where common relational primary keys match in both tables.
13. Generate random numbers from a Normal Distribution using rnorm() in R Programming
Code:
set.seed(42) samples <- rnorm(3, mean = 10, sd = 2) print(samples)
Output:
[1] 12.741917 8.870538 17.262573
Explanation: rnorm generates random samples drawn from normal distributions; set.seed locks random number generators for reproducible results.
14. Count the frequency of unique elements using table() in R Programming
Code:
vec <- c("apple", "banana", "apple", "cherry", "banana", "apple")
counts <- table(vec)
print(counts)
Output:
vec
float apple banana cherry
0 3 2 1
Explanation: table builds contingency frequency distributions counting unique categorical instances in a vector.
15. Write a custom function with error handling using tryCatch() in R Programming
Code:
safe_log <- function(x) {
tryCatch(
expr = { log(x) },
error = function(e) { return("Error occurred") },
warning = function(w) { return("Warning handled") }
)
}
print(safe_log("a"))
Output:
[1] "Error occurred"
Explanation: tryCatch wraps code blocks to gracefully capture errors or warnings during execution without stopping script flow.
16. Iterate through elements using purrr::map_dbl() in R Programming
Code:
library(purrr) numbers <- list(c(1, 2, 3), c(4, 5, 6)) means <- map_dbl(numbers, mean) print(means)
Output:
[1] 2 5
Explanation: purrr::map_dbl applies callback functions across list items, guaranteeing atomic double type vector output.
17. Concatenate strings using paste() and paste0() in R Programming
Code:
str1 <- paste("Hello", "World", sep = "-")
str2 <- paste0("Hello", "World")
print(str1)
print(str2)
Output:
[1] "Hello-World" [1] "HelloWorld"
Explanation: paste connects character strings separated by custom delimiters; paste0 acts as a shortcut using empty spaces.
18. Format dates using the lubridate package in R Programming
Code:
library(lubridate) date_str <- "2026-09-17" parsed_date <- ymd(date_str) print(year(parsed_date)) print(month(parsed_date, label = TRUE))
Output:
[1] 2026 [1] Sep Levels: Jan < Feb < ... < Dec
Explanation: lubridate’s ymd converts year-month-day strings into Date objects, providing helpers like year() or month() for metadata extraction.
19. Sort a data frame by column values using order() in R Programming
Code:
df <- data.frame(a = c(3, 1, 2), b = c("x", "y", "z"))
sorted_df <- df[order(df$a), ]
print(sorted_df)
Output:
a b 2 1 y 3 2 z 1 3 x
Explanation: order yields positional vector index permutations sorted in ascending order, used inside row index brackets to sort tables.
20. Sort a data frame using dplyr::arrange() in R Programming
Code:
library(dplyr) df <- data.frame(value = c(10, 50, 20)) sorted_df <- df %>% arrange(desc(value)) print(sorted_df)
Output:
value 1 50 2 20 3 10
Explanation: arrange sorts tabular rows by specified column criteria, using desc() for descending sort order.
21. Extract regex pattern matches using stringr::str_extract() in R Programming
Code:
library(stringr)
text <- c("Order 123", "Item 4567", "No digits")
digits <- str_extract(text, "\\d+")
print(digits)
Output:
[1] "123" "4567" NA
Explanation: str_extract locates and pulls first occurrences of regular expression pattern matches from text strings.
22. Perform element-wise condition evaluation using ifelse() in R Programming
Code:
scores <- c(85, 55, 70) status <- ifelse(scores >= 70, "Pass", "Fail") print(status)
Output:
[1] "Pass" "Fail" "Pass"
Explanation: ifelse evaluates condition vectors, yielding elements depending on whether boolean evaluation is TRUE or FALSE.
23. Read CSV data into R using read.csv()
Code:
csv_data <- "id,val\n1,100\n2,200" df <- read.csv(text = csv_data) print(df)
Output:
id val 1 1 100 2 2 200
Explanation: read.csv parses comma-separated data sources directly into structured data frames.
24. Convert factors to character vectors and numeric types in R Programming
Code:
f <- factor(c("10", "20", "30"))
nums <- as.numeric(as.character(f))
print(nums)
Output:
[1] 10 20 30
Explanation: Factors must first be cast to character representations via as.character before safely converting them to numeric levels.
25. Calculate matrix multiplication using the %*% operator in R Programming
Code:
A <- matrix(c(1, 2, 3, 4), nrow = 2) B <- matrix(c(2, 0, 1, 2), nrow = 2) res <- A %*% B print(res)
Output:
[,1] [,2] [1,] 2 7 [2,] 4 10
Explanation: The %*% operator executes linear algebra matrix multiplication rather than element-wise scalar arithmetic.
26. Perform K-Means clustering on numeric data in R Programming
Code:
set.seed(123) data <- matrix(rnorm(20), ncol = 2) km <- kmeans(data, centers = 2) print(km$cluster)
Output:
[1] 2 2 2 1 2 2 1 2 2 1
Explanation: kmeans segments multi-dimensional numeric data arrays into cluster assignments based on target centroid counts.
27. Remove duplicate rows using unique() in R Programming
Code:
df <- data.frame(a = c(1, 1, 2), b = c("x", "x", "y"))
clean_df <- unique(df)
print(clean_df)
Output:
a b 1 1 x 3 2 y
Explanation: unique analyzes data vectors or tabular rows and strips duplicate records.
28. Select specific columns using dplyr::select() in R Programming
Code:
library(dplyr) df <- data.frame(x = 1, y = 2, z = 3) selected <- df %>% select(x, z) print(selected)
Output:
x z 1 1 3
Explanation: select subset-extracts target variables from data frames using variable names directly.
29. Find the index of minimum and maximum values using which.min and which.max in R Programming
Code:
vals <- c(45, 12, 89, 33)
min_idx <- which.min(vals)
max_idx <- which.max(vals)
print(paste("Min index:", min_idx, "Max index:", max_idx))
Output:
[1] "Min index: 2 Max index: 3"
Explanation: which.min and which.max identify vector index positions holding lowest and highest values respectively.
30. Construct a basic scatter plot using base R graphics
Code:
x <- 1:5 y <- c(2, 3, 5, 7, 11) plot(x, y, main = "Scatter Plot", xlab = "X-axis", ylab = "Y-axis")
Output:
Plot rendered successfully to graphics device.
Explanation: The base plot() function maps coordinates to graphic rendering devices with customizable title labels.
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.
For Videos, Join Our YouTube Channel: Join Now
Recommended Posts
No Comments