[R] Simulate data for spline/piecewise regression model

Nidhi Kohli nidhik at umd.edu
Thu Nov 5 23:37:30 CET 2009

Dear All,

I am trying to simulate data for a spline/piecewise regression model. I am missing something fundamental in my simulation procedure because when I try to fit my simulated data using the Gauss-Newton method in SAS, I am getting some wacky parameter estimates. Can anyone please check my simulation code and tell me what mistake I am making in generating data for spline model?

Thank you very much for your help.


Here is my code:

#Set the working directory #

setwd("C:/SPLINE MODEL")

#Data Simulation Routine#

subjects = 30 #Sets the sample of subjects for whom the data is to be generated#
knot = 8 #Specifies the value of knot/change point#
beta0 = 3 #Specifies the value of intercept for x <= knot#
beta1 = 8 #Specifies the value of slope for x <= knot#
gamma0 = 6 #Specifies the value of intercept for x > knot#
gamma1 = 5 #Specifies the value of slope for x > knot#

#The following intializes empty (NA) vectors#

X = rep(NA,subjects)
Y = rep(NA, subjects)
DATA = rep(NA, subjects)

#The following sample x.values from uniform distribution#

X = runif(subjects,1,20)

# For loop for computing y-values by comparing each x-value to the knot#

	for (i in 1:30)


	if (X[i] <= knot)
	Y[i] = beta0+beta1*X[i]

	Y[i] = gamma0+gamma1*X[i] 


#Binding/combining the x- and y-values in one data set#

DATA = cbind(X, Y)

#This writes the DATA to a separate file#

write.table(DATA, "SplineData.dat")

More information about the R-help mailing list