0
0
R Programmingprogramming~30 mins

Pipe operator (%>% and |>) in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Pipe Operators %>% and |> in R
📖 Scenario: You are working with a small dataset of fruits and their prices. You want to cleanly and clearly calculate the total cost of all fruits using pipe operators to make your code easy to read.
🎯 Goal: Build a simple R script that uses the pipe operators %>% and |> to calculate the total price of fruits from a named vector.
📋 What You'll Learn
Create a named vector called fruit_prices with exact entries: apple = 2, banana = 1, cherry = 3
Create a variable called price_threshold and set it to 1
Use the %>% pipe operator to filter fruit_prices for prices greater than price_threshold and then sum the filtered prices
Use the |> pipe operator to do the same filtering and summing in a separate variable
Print both results with exact variable names total_price_percent and total_price_base
💡 Why This Matters
🌍 Real World
Pipes help write clear and readable data processing steps, like filtering and summarizing prices in a shopping list.
💼 Career
Data analysts and scientists use pipe operators to write clean, easy-to-understand code for data cleaning and analysis.
Progress0 / 4 steps
1
Create the fruit prices vector
Create a named vector called fruit_prices with these exact entries: apple = 2, banana = 1, cherry = 3
R Programming
Need a hint?

Use the c() function with named elements to create fruit_prices.

2
Set the price threshold
Create a variable called price_threshold and set it to 1
R Programming
Need a hint?

Just assign the number 1 to price_threshold.

3
Calculate total price using %>% pipe
Use the %>% pipe operator to filter fruit_prices for prices greater than price_threshold and then sum the filtered prices. Store the result in total_price_percent. Use the exact code total_price_percent <- fruit_prices %>% .[. > price_threshold] %>% sum()
R Programming
Need a hint?

Use %>% to pass fruit_prices through filtering and then summing.

4
Calculate total price using |> pipe and print results
Use the |> pipe operator to filter fruit_prices for prices greater than price_threshold and then sum the filtered prices. Store the result in total_price_base. Then print both total_price_percent and total_price_base using two separate print() statements.
R Programming
Need a hint?

Use |> with an anonymous function to filter, then pipe to sum(). Use print() to show results.