socialscientist
socialscientist

Reputation: 4272

Predict() + assign() loop across variables

I have estimated several models (a, b) and I want to calculate predicted probabilities for each model using a single data frame (df) and store the predicted probabilities of each model as new variables in that data frame. For example:

a <- lm(y ~ z, df) # estimate model a 
b <- glm(w ~ x, df) # estimate model b
models <- c("a","b")  # create vector of model objects

for (i in models) {
    assign(
            paste("df$", i, sep = ""),
            predict(i, df)
     )}

I have tried the above but receive the error "no applicable method for 'predict' applied to an object of class "character"" with the last word changing as I change class of the predicted object, e.g. predict(as.numeric(i),df).

Any ideas? Ideally I could vectorize this as well.

Upvotes: 0

Views: 949

Answers (1)

MrFlick
MrFlick

Reputation: 206401

You should rarely have to use assign() and $ should not be used with variable names. The [[]] operator is better for dynamic subsetting than $. And it would be easier if you just made a list if the models rather than just their names. Here's an example

df<-data.frame(x=runif(30), y=runif(30), w=runif(30), z=runif(30))

a <- lm(y ~ z, df) # estimate model a 
b <- lm(w ~ x, df) # estimate model b
models <- list(a=a,b=b)  # create vector of model objects

# 1) for loop
for (m in names(models)) {
    df[[m]] <- predict(models[[m]], df)
}

Or rather than a for loop, you could generate all the values with Map and then append with cdbind afterward

# 2) Map/cbind
df <- cbind(df, Map(function(m) predict(m,df), models))

Upvotes: 1

Related Questions