"Vectorizing" this for-loop in R? (suppressing interaction main effects in lm) -
when interactions specified in lm, r includes main effects default, no option suppress them. appropriate , convenient, there instances (within estimators, ratio lhs variables, among others) isn't appropriate.
i've got code fits log-transformed variable response variable, independently within subsets of data.
here silly yet reproducible example:
id = as.factor(c(1,2,2,3,3,3,4,4,4,4,5,5,5,5,6,7,7,8,8,8,9,9,9,9,10)) x = rexp(length(id)) y = rnorm(length(id)) logx = log(x) data = data.frame(id,y,logx) (i in data$id){ sub = subset(data, id==i) #this splits data id m = lm(y~logx-1,data=sub) #this gives me linear (log) fit 1 of id's sub$x.tilde = log(1+3)*m$coef #this linearizes , gives me expected value x=3 data$x.tilde[data$id==i] = sub$x.tilde #this puts main dataset data$tildecoeff[data$id==i] = m$coef #this saves coefficient (i use elsewhere plotting) }
i want fit model following:
y = b(x*id) +e
with no intercept , no main effect of id
. can see loop, i'm interested in expectation of y when x=3, constrained fit through origin (because y (logged) ratio of y[x=something]/y[x=0].
but if specify
m = lm(y~x*as.factor(id)-1)
there no means of suppressing main effects of id
. need run loop several hundred times in iterative algorithm, , loop far slow.
the other upside of de-looping code it'll more convenient prediction intervals.
(please, don't need pious comments how leaving out main effects , intercepts improper -- is, can promise isn't in instance).
thanks in advance ideas!
i think want
m <- lm(y ~ 0 + logx : as.factor(id))
Comments
Post a Comment