What To Buy
Part of the Fundamentals section of Coddy's R journey — lesson 78 of 78.
Challenge
EasyCreate a function called what_to_buy that takes two arguments: budget (a numeric value) and prices (a named vector of item prices). The function should return a character vector containing the names of all items with prices less than or equal to the budget.
If no items are affordable, return an empty character vector using character(0).
You will receive the following inputs:
- The budget amount (a number)
- A comma-separated list of item names (e.g.,
apple,banana,steak,bread) - A comma-separated list of corresponding prices (e.g.,
2,1,15,3)
Parse the inputs to create a named vector of prices, call your function, and print the result. Use print() to display the returned character vector.
For example, if the input is:
5
apple,banana,steak,bread
2,1,15,3The output should be:
[1] "apple" "banana" "bread"If the input is:
10
laptop,phone,tablet
999,599,399The output should be:
character(0)Hints:
- Use
strsplit(input, ",")[[1]]to split comma-separated strings into vectors - Use
as.numeric()to convert the price strings to numbers - Use
names(prices) <- item_namesto create a named vector - Use logical indexing with
names()to extract affordable item names
Try it yourself
# Read input
con <- file("stdin", "r")
budget <- as.numeric(suppressWarnings(readLines(con, n = 1)))
item_names_input <- suppressWarnings(readLines(con, n = 1))
prices_input <- suppressWarnings(readLines(con, n = 1))
close(con)
# Parse the inputs
item_names <- strsplit(item_names_input, ",")[[1]]
price_values <- as.numeric(strsplit(prices_input, ",")[[1]])
# Create a named vector of prices
prices <- price_values
names(prices) <- item_names
# TODO: Write your function what_to_buy below
# The function should take budget and prices as arguments
# and return a character vector of affordable item names
# Call the function and print the result
result <- what_to_buy(budget, prices)
print(result)All 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