</>
Skip to content
R lessons (35/41)

R — Data Visualization

Missing data

library(dplyr)

df <- data.frame(
  x = c(1, 2, NA, 4, 5),
  y = c(NA, 2, 3, NA, 5)
)

# Check for NAs
is.na(df$x)
sum(is.na(df))

# Remove NAs
na.omit(df)
df %>% filter(!is.na(x))

# Impute with mean
df$x[is.na(df$x)] <- mean(df$x, na.rm = TRUE)

TidyNA

library(naniar)

# Visualize missing data
gg_miss_var(df)

# Impute
df_imputed <- df %>%
  miss_var_ribute(amount = "miss")

Outliers

# IQR method
find_outliers <- function(x) {
  q1 <- quantile(x, 0.25)
  q3 <- quantile(x, 0.75)
  iqr <- q3 - q1
  lower <- q1 - 1.5 * iqr
  upper <- q3 + 1.5 * iqr
  x < lower | x > upper
}

# Remove outliers
df <- df[!find_outliers(df$x), ]

String cleaning

library(stringr)

# Trim whitespace
str_trim("  hello  ")

# Replace patterns
str_replace_all("hello world", " ", "_")

# Case conversion
str_to_lower("HELLO")
str_to_upper("hello")

Mini Practice

Write R code that:

  1. Detects and handles missing values
  2. Imputes missing data
  3. Identifies outliers with IQR
  4. Cleans strings with stringr

Up Next

In the next lesson, you'll learn about Pipe Operator — chaining operations.

Related Topics

Frequently Asked Questions about Data Visualization

What is Data Visualization in R?

Data Visualization is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Data Visualization?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Data Visualization.

Why is Data Visualization important in R?

Data Visualization is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.