0

I want to create a function with a for-loop such that every variable of my dataframe is plotted (scatter plot) against the variable main_variable (using ggplot2)

The dataframe:

       main_variable          a   b    c   d
1              7  42.857143 210  510 120
2              3 115.714286 180  810 450
3              5  21.428571 120  270  NA
4              5  17.142857 540  660  NA
5              2  20.000000  NA  100  40
6              2  21.428571  60   60 150
7              0   5.714286  NA   NA 190
8              2   8.571429 120  180  NA
9              4  17.857143 810  935  60
10             3  21.428571 900 1050  NA

the Function I've come up with so far is:

scatter <-  function(df) {
  for(i in 2:ncol(df)){
    col <- names(df)[i]
    na.omit(col)
    as.character(quote(col))
    scp <- ggplot(df, aes(x = main_variable, y = col)) + 
           geom_jitter(size = 0.25, height = 0.25) + 
           scale_x_continuous(limits = c(0, 7)) + 
           scale_y_discrete(limits = c(0, max(df[, col]))) + 
           geom_smooth(method = "lm", colour = "Red")
    plot(scp)
    }
}
scatter(dataframe)

but then the error message appears:

Error: Discrete value supplied to continuous scale

The values of main_variable can only take on one of 8 values: 0, 1, 2, 3, 4, 5, 6, or 7. The values of all other variables may be between 0 and 5'000.

However, running

dataframe[1:ncol(dataframe)] <- as.numeric(unlist(dataframe[1:ncol(dataframe)]))

does not solve the problem. (I'm using 1:ncol(dataframe) because I do not want to convert and use all variables of my real dataframe.)

Does anyone know how to fix this?

Thank you.

fabha
  • 111
  • 7
  • 1
    this seems inimically opposed to the philosophy of `ggplot2` and even `tidy` data that would be to `gather` your data and the use the facet functions instead e.g. `facet_wrap(~col)`. No loops! – Stephen Henderson Apr 06 '17 at 13:28
  • it should be: scale_x_discrete, scale_y_continuous, but this doesn't solve the problem. – fabha Apr 06 '17 at 13:28
  • Use `aes_string(x = "main_variable", y = col)`. You can't use variables with character values in an `aes()` statement; `aes()` expects symbols that it can look up in the main data.frame. – MrFlick Apr 06 '17 at 13:51
  • Thanks for your comments. @StephenHenderson, why no loops? Loops and ggplot2 worked in another function I wrote. I tried facet_wrap(~col), but then the following error message appears: "Fehler in combine_vars(data, params$plot_env, vars, drop = params$drop) : At least one layer must contain all variables used for facetting". Could you specify how I should use facet_wrap? – fabha Apr 10 '17 at 07:14

0 Answers0