Recap - Product List
Part of the Fundamentals section of Coddy's R journey — lesson 75 of 78.
Challenge
EasyYou will receive four lines of input:
- A product name (e.g.,
Wireless Headphones) - A price (e.g.,
79.99) - A stock quantity (e.g.,
25) - A discount percentage to apply (e.g.,
20)
Perform the following operations:
- Create a named list called
productwith elements:name(character),price(numeric),stock(numeric), andavailable(set toTRUEif stock is greater than 0, otherwiseFALSE) - Print the product name using the
$operator - Calculate the discounted price (original price minus the discount percentage) and update the
priceelement - Add a new element called
discountedwith the valueTRUE - Reduce the
stockby 1 (simulating a purchase) - Remove the
availableelement from the list - Print the final list
For example, if the inputs are:
Smart Watch
150
10
25The output should be:
[1] "Smart Watch"
$name
[1] "Smart Watch"
$price
[1] 112.5
$stock
[1] 9
$discounted
[1] TRUEExplanation:
- Original price 150 with 25% discount: 150 - (150 * 25/100) = 112.5
- Stock reduced from 10 to 9
- The
availableelement was removed from the final list
Try it yourself
# Read input
con <- file("stdin", "r")
product_name <- suppressWarnings(readLines(con, n = 1))
price <- as.numeric(suppressWarnings(readLines(con, n = 1)))
stock <- as.numeric(suppressWarnings(readLines(con, n = 1)))
discount_percentage <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)
# TODO: Write your code below
# 1. Create a named list called 'product' with elements: name, price, stock, and available
# 2. Print the product name using the $ operator
# 3. Calculate the discounted price and update the price element
# 4. Add a new element called 'discounted' with value TRUE
# 5. Reduce the stock by 1
# 6. Remove the 'available' element from the list
# 7. Print the final listAll lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values