Reputation: 165
I've been trying to create a for loop that will go through my data frame and make the same plot for each of the individual IDs I have. Here's some sample data:
TJID1 <- c("TJ22", "TJ22", "TJ23", "TJ23", "TJ23", "TJ24", "TJ24")
Day <- c("2005-11-22", "2005-11-23", "2006-12-01", "2006-12-02", "2006-12-03","2005-07-08", "2005-07-08")
Mean.Depth <- c (2, 2, 3, 4, 5, 6, 6)
SE.Depth <- c(1, 1, 2, 2, 1, 2, 2)
sample <- cbind(TJID1, Day, Mean.Depth, SE.Depth)
sample <- as.data.frame(sample)
I have each individual as a different TJ number, and then for each TJ they have different daily depth means. The days change for each individual. I have been able to subset the main data frame by each individual TJ TJ22 <- sample [sample$TJID1 == "TJ22", ]
. My code from the plot is then (using the subsetted data frame):
DailyMeans_TJ22 <- ggplot(TJ22, aes(x=Day, y=Mean.Depth))+
geom_point()+
geom_line()+
geom_errorbar(aes(ymin=Mean.Depth-1.96*SE.Depth, ymax=Mean.Depth+1.96*SE.Depth), width = 0.5, col="red")
I want to create a for loop that just cycles through each individual and makes the same plot. This is what I have so far:
var_list = combn(names(sample) [3:4], 3, simplify=FALSE)
plot_list = list()
for (i in unique (sample$TJID1)){
TJ <- sample[sample$TJID1== i,]
p = ggplot(TJ, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
geom_point()+
geom_line()
plot_list[[i]] = p
}
But that literally just gives me nothing. Any help is appreciated!
Upvotes: 0
Views: 1847
Reputation: 39154
Here is an idea. We can design a function to subset sample
and then create and return a plot. After that, we used lapply
to loop through the unique values in TJID1
.
Please notice that in your original sample
data frame, those numeric columns are expressed as factor. I changed the way to create the sample
data frame to fix that. One final note. sample
is a bad name because there is a function in R called sample
, which causes confusion. Please name your data frame using other names that do not match other function names in the future.
# Load package
library(ggplot2)
# Create example data frame
sample <- data.frame(TJID1 = c("TJ22", "TJ22", "TJ23", "TJ23", "TJ23", "TJ24", "TJ24"),
Day = c("2005-11-22", "2005-11-23", "2006-12-01", "2006-12-02", "2006-12-03","2005-07-08", "2005-07-08"),
Mean.Depth = c (2, 2, 3, 4, 5, 6, 6),
SE.Depth = c(1, 1, 2, 2, 1, 2, 2),
stringsAsFactors = FALSE)
# Design a function
gg_fun <- function(parameter, dt){
p <- ggplot(dt[dt$TJID1 == parameter, ], aes(x=Day, y=Mean.Depth))+
geom_point()+
geom_line()+
geom_errorbar(aes(ymin=Mean.Depth-1.96*SE.Depth, ymax=Mean.Depth+1.96*SE.Depth), width = 0.5, col="red") +
ggtitle(parameter)
return(p)
}
# Apply the function
plot_list <- lapply(unique(sample$TJID1), gg_fun, dt = sample)
Upvotes: 1