如何用R求解方程By=Ax+C的系数A、B并计算均值和标准差
Hey there! Let's walk through exactly how to implement this in R. We'll break it down into clear, actionable steps:
1. Define Your Input Data
First, let's start by defining the vectors you provided:
# Input data vectors y <- c(-9216.656, -9134.369, -9186.813, -8780.633, -9006.787) x <- c(908.4656, 932.6687, 1015.0424, 816.9116, 703.2510) C <- c(-8.965961, -8.883207, -8.935910, -8.546677, -8.766842)
2. Generate All Pairwise Index Combinations
We need every possible pair of data points to build our 10 systems of equations. The combn() function makes this easy—it generates all unique 2-element combinations of indices from our 5 data points:
# Get all 10 pairwise index combinations (5 choose 2) pair_indices <- combn(length(x), 2)
3. Solve Each Linear System
For each pair of indices, we'll rewrite the equation By = Ax + C into the standard linear form Ax - By = -C, then construct the coefficient matrix and constant vector to solve for A and B using R's built-in solve() function. We'll store all solutions in a data frame:
# Initialize an empty data frame to store results results <- data.frame(A = numeric(), B = numeric()) # Loop through each pair of indices for (i in 1:ncol(pair_indices)) { # Extract the two indices for the current pair idx1 <- pair_indices[1, i] idx2 <- pair_indices[2, i] # Build the coefficient matrix for the system: # [x1 -y1] [A] = [-C1] # [x2 -y2] [B] [-C2] coeff_matrix <- matrix( c(x[idx1], -y[idx1], x[idx2], -y[idx2]), nrow = 2, byrow = TRUE ) # Build the constant term vector const_vector <- c(-C[idx1], -C[idx2]) # Solve the linear system and store the results solution <- solve(coeff_matrix, const_vector) results <- rbind(results, data.frame(A = solution[1], B = solution[2])) } # Print all 10 A/B pairs cat("All 10 sets of A and B:\n") print(results)
4. Calculate Mean & Standard Deviation
Finally, we'll compute the mean and standard deviation for both A and B using base R functions:
# Compute summary statistics summary_stats <- data.frame( Metric = c("Mean", "Standard Deviation"), A = c(mean(results$A), sd(results$A)), B = c(mean(results$B), sd(results$B)) ) # Print the summary stats cat("\nSummary statistics for A and B:\n") print(summary_stats)
Quick Notes:
- The
solve()function works reliably here because each pairwise system is a 2x2 matrix (two equations, two unknowns) with no linear dependence between the equations. - The
combn()function ensures we only get unique pairs (no duplicates like (1,2) and (2,1)), which gives us exactly the 10 distinct systems we need.
内容的提问来源于stack exchange,提问作者imtaiky

