Search code examples
rfor-loopdplyrapplypurrr

How to plot series of xyplot() via a for loop or alternative iterative method


I have the following dataset:

df <- structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Vid = c(0, 
0, 1, 1, 0, 1, 1, 0, 0, 1), Mus = c(1, 0, 1, 1, 0, 1, 0, 0, 1, 
1), Rea = c(1, 0, 1, 1, 1, 1, 1, 0, 0, 0), Ema = c(1, 0, 0, 1, 
0, 0, 0, 1, 0, 0), SMS = c(1, 0, 1, 1, 0, 0, 0, 0, 0, 0), tel = c(0, 
0, 0, 1, 0, 0, 0, 0, 1, 0), MMT = c(53, 17.5, 48.5, 40, 19.5, 
37.5, 25, 17.5, 22.5, 18.5), rec = c(0.986090887933027, 0.0680321184694875, 
0.968640096476421, 0.865412998525399, 0.100122305069044, 0.802091434784794, 
0.261753760392736, 0.0680321184694875, 0.173118039249657, 0.0826713725018173
), MM_levels = c("HMM", "IMM", "HMM", "IMM", "IMM", "IMM", "IMM", 
"IMM", "IMM", "IMM")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

and I am trying to represent the xyplot() iteratively via the following for loop:

for(i in names(df[c(2:7,9)])){
  xyplot(x = i,
          y = "rec",
          data = as.data.frame(df),
          necessity = TRUE,
          jitter = TRUE,
          xlab = names(i),
          ylab = "rec")
}

I do not know why but it seems that despite I am able to run this code with no errors, I can not produce the sequence of plot that I am expecting. Can anyone suggest how to adjust the loop or an alternative method different from loop to get these xplots?


Solution

  • as @MrFlick suggested, you need to wrap these plotting functions in print() in a for loop:

    for(i in names(df[c(2:7,9)])){
    print(
    xyplot(x = i,
              y = "rec",
              data = as.data.frame(df),
              necessity = TRUE,
              jitter = TRUE,
              xlab = names(i),
              ylab = "rec")
    ) # close parenthesis of print function
    }