Menu
Coddy logo textTech

What To Buy

Part of the Fundamentals section of Coddy's R journey — lesson 78 of 78.

challenge icon

Challenge

Easy

Create 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:

  1. The budget amount (a number)
  2. A comma-separated list of item names (e.g., apple,banana,steak,bread)
  3. 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,3

The output should be:

[1] "apple"  "banana" "bread"

If the input is:

10
laptop,phone,tablet
999,599,399

The 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_names to 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