« How to change language setting of R on Windows | Main | The silence in Davos »

January 10, 2011

$ operator not defined for this S4 class

I was trying to reproduce Figure3.11 in Gelman and Hill (2006).  I got an error message, "$ operator not defined for this S4 class."  (R 2.12.1)  I have no idea what a class is.  I changed "$" in their codes into "@" after I read this.  It seems it works fine.  I don't know why, though.  If R were a person, I would say horrible things to it, but it is a program, so....I just have to live with it. 

> curve (coef(fit.2)[1] + coef(fit.2)[2]*x, add=TRUE, col="red")
> fit.3 <- lm (kid_score ~ mom_hs + mom_iq)
> beta.hat <- coef (fit.3)
> beta.sim <- sim (fit.3)$coef
Error in sim(fit.3)$coef : $ operator not defined for this S4 class

#So I try "@" instead.

> beta.sim <- sim (fit.3)@coef
> kidscore.jitter <- jitter(kid_score)
>
> jitter.binary <- function(a, jitt=.05){
+    ifelse (a==0, runif (length(a), 0, jitt), runif (length(a), 1-jitt, 1))
+ }
> jitter.mom_hs <- jitter.binary(mom_hs)
> par (mfrow=c(1,2))
> plot (mom_iq, kid_score, xlab="Mother IQ score", ylab="Child test score",
+   pch=20, xaxt="n", yaxt="n")
> axis (1, c(80,100,120,140))
> axis (2, c(20,60,100,140))
> for (i in 1:10){
+   curve (cbind (1, mean(mom_hs), x) %*% beta.sim[i,], lwd=.5, col="gray",
+     add=TRUE)
+ }
> curve (cbind (1, mean(mom_hs), x) %*% beta.hat, col="black", add=TRUE)
> plot (jitter.mom_hs, kidscore.jitter, xlab="Mother completed high school",
+   ylab="Child test score", pch=20, xaxt="n", yaxt="n")
> axis (1, seq(0,1))
> axis (2, c(0,50,100,150))
> for (i in 1:10){
+   curve (cbind (1, x, mean(mom_iq)) %*% beta.sim[i,], lwd=.5, col="gray",
+     add=TRUE)
+ }
> curve (cbind (1, x, mean(mom_iq)) %*% beta.hat, col="black", add=TRUE)
>
>

« How to change language setting of R on Windows | Main | The silence in Davos »

Comments

Your page came up on google when I searched the error, I've been having the same problem going through the same book. thank you.

Posted by: Random guy | February 04, 2012 03:01 PM

Thanks a bunch! I also found your blog through search. It solved my problem.

Posted by: Another random guy | July 02, 2012 10:30 PM

Thank you very much. This works great.

Posted by: Ran Ji | July 08, 2013 01:09 PM

Post a comment



(Not displayed with comment.)


Comments are moderated, and will not appear on this weblog until the author has approved them.



« How to change language setting of R on Windows | Main | The silence in Davos »