I needs to create a qqplot using facets by row and column. I understand how to facet plot with columns and rows, but I am not sure how to set up my data. Ultimately, I want to group my dataset by column and row, then sort the 'Modeled' results and 'Observed' results in ascending order while adding a column with the 'row' group and a column with the 'column' group.
I have been trying to modify the solution to this question, Faceted qqplots with ggplot2, , but I am not very familiar with lapply so maybe I just missed something.
Here is the code I have been working with:
#Dummy Data:
df <- mtcars
# Name columns as I have in my real data
df$rows <- df$cyl
df$columns <- df$gear
df$Modeled <- df$wt
df$Observed <- df$mpg
# Function to sort data while maintaining the rows & columns for use in facet later.
dat_sort <- do.call("rbind",
sapply(list(unique(df$rows), unique(df$columns)),
FUN = function(x) {
data.frame(rows = x[[1]],
columns = x[[2]],
Observed = sort(df$Observed[df$rows == x[[1]] & df$columns == x[[2]]]),
Modeled = sort(df$Modeled[df$rows == x[[1]] & df$columns == x[[2]]])
)
}
))
I don't get an error, but my output is definitely not what I was expecting. My output should look like this: (with correct column names)
rows columns Observed Modeled
6 4 17.8 2.620
6 4 19.2 2.875
6 4 21.0 3.440
6 4 21.0 3.440
4 3 21.5 2.465
8 5 15.0 3.17
8 5 15.8 3.57
Output from code:
[,1] [,2] [,3] [,4]
[1,] 6.000 6.000 6.000 6.000
[2,] 4.000 4.000 4.000 4.000
[3,] 17.800 19.200 21.000 21.000
[4,] 2.620 2.875 3.440 3.440
[5,] 4.000 4.000 4.000 4.000
[6,] 3.000 3.000 3.000 3.000
[7,] 21.500 21.500 21.500 21.500
[8,] 2.465 2.465 2.465 2.465
Any help would be most appreciated!
Thanks!