Harr1ls
Harr1ls

Reputation: 81

for loop in R - generate different graphics

If I have a set of data for different samples (x) and a fixed y, like:

> x1 <- c(5,6,7,8)
> x2 <- c(9,7.8,6,8)
> x3 <- c(7,3,5,1)x 
> y <- c(20,21,20,50)

If I want to try to plot these data like (x1 ~ y), (x2 ~ y), (x3 ~ y)

> x_data <- data_frame(x1, x2, x3)
> 
> for (i in seq_along(x_data)) {   
>   model <- lm(x_data[i] ~ y)
>   plot(model) 
> }

However, this is not working and I get the following error:

Error in model.frame.default(formula = x_data[i] ~ y, drop.unused.levels = TRUE) : 
variable lengths differ (found for 'x_data')

I am trying to picture them to check if there is a dependency on the values.

Upvotes: 1

Views: 31

Answers (2)

Parfait
Parfait

Reputation: 107652

Consider reformulate and binding all vectors into a data frame to use with data argument of lm:

model_data <- data.frame(y, x1, x2, x3)

# ITERATE ACROSS COLUMN NAMES, IGNORING FIRST
for (x in colnames(model_data[-1])) {   
  model <- lm(reformulate("y", response=x), data=model_data)
  plot(model) 
}

Upvotes: 1

akrun
akrun

Reputation: 887213

We can create the formula with paste

par(mfrow = c(3, 4))
for (i in seq_along(x_data)) {   
    model <- lm(as.formula(paste(names(x_data)[i],  "~ y")), data = x_data)
      plot(model) 
     }

enter image description here


or with reformulate

par(mfrow = c(3, 4))
for (i in seq_along(x_data)) {   
    model <- lm(reformulate("y", response = names(x_data)[i]), data = x_data)
      plot(model) 
     }

Upvotes: 0

Related Questions