关于m个节点的n次B样条数量及R语言bs函数计算疑问
bs() Behavior 1. How many n-degree B-splines are there with m nodes?
The number of B-spline basis functions of degree n depends on how you define "nodes" (knots):
- Using the full clamped knot vector: This is the standard definition where each boundary knot is repeated
n+1times (to ensure the spline is "clamped" at the edges, matching polynomial regression behavior there). Ifmis the total length of this full vector (including repeated knots), the number of basis functions is:number of B-splines = m - n - 1 - Using distinct knots: If you have
kdistinct internal knots plus 2 distinct boundary knots (the min and max of your data), the number of basis functions (including an intercept term) is:
If you exclude the intercept (common in regression to avoid multicollinearity), subtract 1 from this total.number of B-splines = k + n + 1
2. Resolving the R bs() Discrepancy
Let's break down why your formula gave an unexpected result with bs(speed, knots=c(14, 20), degree=2):
Your Key Misunderstandings:
You only counted internal knots in the formula: Your original formula refers to the full clamped knot vector, not just the internal knots you specified. R's
bs()automatically adds boundary knots (the min and max of yourspeeddata) and repeats each boundary knotdegree+1times (3 times for degree 2) to form the clamped vector.- For example, if
speedranges fromS_mintoS_max, the full knot vector is:[S_min, S_min, S_min, 14, 20, S_max, S_max, S_max](length 8). - Applying your formula correctly here:
8 - 2 -1 =5(this is the total number of basis functions including the intercept).
- For example, if
R's default excludes the intercept: The
bs()function usesintercept=FALSEby default, which removes one basis function to avoid multicollinearity with a global intercept in regression models.- So 5 total basis functions minus 1 gives 4, which matches what you observed.
Correct Formula Application for R:
If you want to use your original formula with R's output:
- Count the full clamped knot vector length (including repeated boundaries) instead of just internal knots.
- Adjust for the
interceptsetting if needed.
Alternatively, use the practical distinct-knot formula:
- With 2 internal knots and degree 2, total basis functions (including intercept) are
2+2+1=5. Subtract 1 for R's defaultintercept=FALSEto get 4.
内容的提问来源于stack exchange,提问作者Jack

