Skip to content

Commit

Permalink
replace as.character with deparse, as per pull request rmcelreath#285
Browse files Browse the repository at this point in the history
Related pull request
fix for issue with link not adding intercept for linear models
rmcelreath#285

I'm having trouble using sim with models that have index variables.  Some debug code is crashing, and I think this may fix it.
  • Loading branch information
rxg authored Dec 7, 2022
1 parent 783d111 commit 2c4dba4
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion R/sim.r
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ sim_core <- function( fit , data , post , vars , n , refresh=0 , replace=list()
f <- fit@formula[[1]]
for ( i in 1:length(fit@formula) ) {
f <- fit@formula[[i]]
left <- as.character( f[[2]] )
left <- deparse( f[[2]] )
if ( left==var ) {
if ( debug==TRUE ) print(f)
break
Expand Down

1 comment on commit 2c4dba4

@rxg
Copy link
Owner Author

@rxg rxg commented on 2c4dba4 Dec 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is an example R script that was crashing but now seems to work:

library(rethinking)

# Nancy Howell's Dobe !Kung data
data(Howell1)
d <- Howell1[Howell1$age >= 18, ]
d$sex <- d$male + 1

model5 <- alist(
    w ~ dnorm(mu, sigma),
    mu <- a[sex] + b[sex] * (h - hbar),
    a[sex] ~ dnorm(60, 10), # intercept: average adult weight in kg (wikipedia)
    b[sex] ~ dlnorm(0, 1),  # slope: change in weight per change in height
    sigma ~ dunif(0, 10),   # displacement

    h ~ dnorm(hmu, hsigma),
    hmu <- ha[sex],
    ha[sex] ~ dnorm(170, 15), # intercept: average adult height in cm
    hsigma ~ dunif(0, 10)      # displacement
)
dat <- list(w = d$weight, h = d$height,  hbar = mean(d$height), sex = d$sex)
fit5 <- quap(model5, data = dat)
precis(fit5, depth = 2)

# This is similar to McElreath 2022 Lecture 04, 49:39, but isn't working
hwsim <- sim(fit5, data = list(sex = c(1, 2), hbar = mean(d$height)),
     vars = c("h", "w"))
# seems to be dying in simcore because
# as.character turns a[s] into a vector c("[","a","s")

Please sign in to comment.