0

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!

Suusie
  • 149
  • 9
  • 1
    you should try to use the list of data frames for each species that you created: `lapply(DF2, function(data) plot(y ~ x, data = data, main = unique(data$Species), ...))` – rawr Oct 22 '21 at 17:29
  • How can I make them visible? each species separate ;) – Suusie Oct 22 '21 at 17:35
  • 2
    For @rawr's comment, please see https://stackoverflow.com/a/24376207/3358227, *many* good examples of working with data in a list of frames. – r2evans Oct 22 '21 at 17:37
  • 1
    you already have a list of data frames with each species separate, so when you run `plot(...)` in the `lapply`, you will get a new plot for each species – rawr Oct 22 '21 at 17:37
  • Is there a way for me to extract them separately afterwards? – Suusie Oct 22 '21 at 18:34

1 Answers1

1

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)
}

iris separated plots

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])).

r2evans
  • 141,215
  • 6
  • 77
  • 149