Magrittr Pipes

Data ManipulationPipesFree Lesson

Advertisement

Introduction

The magrittr package provides pipe operators (%>%) for chaining operations. Pipes make code more readable.

Basic Pipe

library(magrittr)

# Without pipe
result <- select(filter(df, x > 5), name)

# With pipe
result <- df %>%
  filter(x > 5) %>%
  select(name)

Pipe Variations

# Tee pipe - shows intermediate result
df %>%
  filter(x > 5) %T>% 
  print() %>%
  summarize(mean(x))

# Assignment pipe - assign and pass
df %<>% 
  filter(x > 5) %>%
  mutate(x = x * 2)

# Exposition pipe - expose variables
df %$%
  cor(x, y)

Pipe with Multiple Arguments

# Using . for placeholder
df %>%
  lm(y ~ x, data = .)

# Multiple placeholders
df %>%
  select(x, y) %>%
  colMeans()

Summary

Pipes create readable data processing pipelines. Use them for cleaner, more maintainable code.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement