使用rpy2在Python中执行nls回归遇RRuntimeError求助
Let's break down why you're hitting that RRuntimeError and fix it step by step. The error message parameters without starting value in 'data': rates, count tells us R's nls can't find the variables rates and count you referenced in your formula—here's how to resolve this:
Root Cause
Your original code extracts count and rates as separate R vectors, but you didn't tell nls where to find these variables. Additionally, your formula uses these Python-assigned aliases instead of the actual column names from your data frame, and you didn't pass the data frame to nls's data parameter (which nls relies on to locate variables).
Fixed Code
Here's the revised code that should work correctly:
import pandas as pd import rpy2.robjects as ro from rpy2.robjects.packages import importr from rpy2.robjects import pandas2ri pandas2ri.activate() # Load your data (use your local file path) dfData = pd.read_csv('C:\\Users\\nick\\Desktop\\ratedata.csv') rdf = pandas2ri.py2ri(dfData) # Define initial parameter values for the model start_params = ro.ListVector({'a': 0.5, 'b': 1.1}) # Import required R packages with name translations base = importr('base', robject_translations={'with': '_with'}) stats = importr('stats', robject_translations={'format_perc': '_format_perc'}) # Update formula to use actual column names from your data frame my_formula = stats.as_formula('Successes ~ 1 - (1 / (10^(a * Trials ^ (b - 1))))') # Run nls with explicit data parameter, weights, and start values fit = stats.nls( formula=my_formula, data=rdf, weights=rdf.rx(True, 'Trials'), start=start_params ) # Extract fitted parameters into Python variables fit_params = dict(zip(fit.names, list(fit))) a_fitted = fit_params['a'] b_fitted = fit_params['b'] print(f"Fitted parameter a: {a_fitted}") print(f"Fitted parameter b: {b_fitted}")
Key Changes Explained
- Formula Alignment: We replaced
ratesandcountwith your actual data frame column names (SuccessesandTrials). This ensuresnlscan locate the variables in the provided data frame. - Data Parameter: Adding
data=rdftellsnlsto look for all formula variables within your R data frame, eliminating the "variable not found" error. - Explicit Weights: We directly reference the
Trialscolumn fromrdffor weights, keeping all data references consistent within the R data frame context. - Parameter Extraction: Converting the fitted R object to a Python dictionary makes it easy to pull out the estimated
aandbvalues for your confidence interval calculations.
Once you run this code, you'll get the fitted parameter values you need to proceed with building your confidence intervals in Python.
内容的提问来源于stack exchange,提问作者Nicholas

