samot79 samot79 - 1 month ago 5
R Question

Looping over dataframe to create scatterplots

Data frame

x <- data.frame(id = c("A","B","C"), x_predictor = c(5,6,7), x_depended = c(5.5, 6.5, 7.5), y_predictor=c(2,3,2), y_depended=c(3,3,2), z_predictor=c(12,10,12), z_depended=c(14,11,13))

> x
id x_predictor x_depended y_predictor y_depended z_predictor z_depended
1 A 5 5.5 2 3 12 14
2 B 6 6.5 3 3 10 11
3 C 7 7.5 2 2 12 13


I would like to create a scatterplot for each level on ID and for each pair depended and predictor.

I have created a for loop where I loop over unique levels in ID, but how can I loop over pairs of depended and predictor?

uni <- unique(x$id)

for (p in uni){
print(ggplot(x[x$id==p], aes(y = x_depended,x = x_predictor))+geom_point()
}


I would like to plot depended vs predictor. Depended will always be in following column to its predictor.

Answer

This code will plot three different scatter plots where each plot will contain the different columns that you have in your data frame.

require(ggplot2)
x_plots <- list()
uni <- unique(x$id)
uni_counter <- 0
i <- 0
for (colnum in seq(2, 6, 2)) {
  x_col <- names(x)[colnum]
  y_col <- names(x)[colnum + 1]
  # Retrieve the current uni.
  curr_uni <- uni[uni_counter]
  # Increment our counters
  uni_counter <- uni_counter + 1
  i <- i + 1
  # Create the ggplot command,
  # the command is created dynamically so that we can iterate through
  # different columns in our data frame.
  ggplot_cmd <- paste0("x_plots[[i]] <- ggplot(x[x$id == curr_uni], aes(y = ", y_col, ", x = ", y_col, "))+geom_point()")
  # Evaluate each plot.
  eval(parse(text = ggplot_cmd))
}

You can than load the multiplot() function posted here to draw all the generated plots in one figure using:

multiplot(plotlist = x_plots)

Hope this helps.