求助:开发R语言加密货币跨币种转换函数遇报错
Let's walk through the errors in your code and fix them step by step. I'll break down what's going wrong, explain the fixes, and give you a robust working version.
First, Let's Diagnose the Errors
1. object 'x' not found / object 'z' not found
This usually happens if you didn't pass arguments correctly when calling the function. For example:
- If you called
convert(, 10, "Ethereum")(missing the first argument) - Or mixed up the order of arguments, e.g.,
convert("Bitcoin", "Ethereum", 10)(you put the transfer amount last instead of second)
Double-check that you're calling the function with the correct order:convert("转出货币名", 转出数量, "转入货币名")
2. attempt to select less than one element in get1index
This error pops up when the currency name you passed doesn't exist in your mdata$id column. The which() function returns an empty vector when it can't find a match, and trying to grab [[1]] from an empty vector causes this crash. We need to add a check for this case.
3. Critical Logic Error in Conversion Calculation
Your current calculation is doing this:
conversion <- currency_price[[index_z]] * amount return(conversion / currency_price[[index_z]])
Which simplifies to just returning amount—that's why your function isn't actually converting anything! The correct formula for cross-currency conversion is:
转入数量 = (转出数量 × 转出货币单价) ÷ 转入货币单价
Fixed Function with Error Handling
Here's the corrected version of your function, with safeguards and proper logic:
convert <- function(from_currency, amount, to_currency, data = mdata) { # Validate input amount is numeric if (!is.numeric(amount) || amount <= 0) { stop("Error: Amount must be a positive number!") } # Get price and ID columns from the dataset price_col <- data$current_price id_col <- data$id # Find indices for from and to currencies from_index <- which(id_col == from_currency) to_index <- which(id_col == to_currency) # Check if currencies exist in the dataset if (length(from_index) == 0) { stop(paste("Error: Currency", from_currency, "not found in the dataset!")) } if (length(to_index) == 0) { stop(paste("Error: Currency", to_currency, "not found in the dataset!")) } # Get the prices (take first match if there are duplicates) from_price <- price_col[[from_index[1]]] to_price <- price_col[[to_index[1]]] # Calculate conversion: total value in EUR / target currency price converted_amount <- (amount * from_price) / to_price return(converted_amount) }
Key Improvements Explained
- Descriptive Parameter Names: Changed
x,ztofrom_currency,to_currencyso the function is easier to read and use. - Input Validation: Checks that
amountis a positive number, and that both currencies exist in your dataset—this gives clear error messages instead of confusing crashes. - Proper Conversion Logic: Implements the correct formula to calculate the amount of the target currency you'll get.
- Flexible Dataset Input: Added an optional
dataparameter so you can pass different datasets if needed (defaults tomdatafor your use case). - Handles Duplicates: If there are multiple entries with the same currency ID, it uses the first match (you can adjust this if needed for your dataset).
Example Usage
If your mdata has "bitcoin" and "ethereum" in the id column, you can call the function like this:
convert(from_currency = "bitcoin", amount = 2, to_currency = "ethereum")
内容的提问来源于stack exchange,提问作者Giulia Montorsi

