Reputation: 149
Hello, I have a large dataframe which I split following the next code:
DF2 <- split(df, df$Species)
new_names <- as.character(unique(df$Species))
for (i in 1:length(DF2)) {
assign(new_names[i], DF2[[i]])
}
Giving me many dataframes with each having the same starting letters DF2Fish-XX with the XX being the unique species:
Now I want to have a loop function to create multiple plots using the following code to for each Species (unique dataframe):
par(mfrow=c(2,2))
DF2Plot <- function(index){plot(DF2Fish-XX[,index] ~ DF2Fish-XX$Year,
main=names(DF2Fish-XX[index]), xlab= "Years",
ylab = "Trophic position", type="b", xlim=range(1930:2020), ylim=range(2:5))}
lapply(2:5, FUN= DF2Plot)
Is there a way to have the second part of the script (creating the plot) in a loop for each unique species/dataframe created in the first part of code?
Any help is welcome.
Thanks in advance!
Upvotes: 0
Views: 340
Reputation: 160417
I'll demonstrate using iris
.
irisL <- split(iris, iris$Species)
names(irisL)
# [1] "setosa" "versicolor" "virginica"
par(mfrow = c(2, 2))
for (nm in names(irisL)) {
plot(Sepal.Length ~ Sepal.Width, data=irisL[[nm]], main=nm)
}
If your list of frames is not named, then you can index this way:
for (ind in seq_along(irisL)) {
# ...
}
though you will need a direct way to infer the name (perhaps as.character(irisL[[ind]]$Species[1])
).
Upvotes: 1