I'll offer some much more general advice on learning R. Most users come to it with prior background in procedural/imperative programming. It's natural that we want to apply those tools to using R. And they do have a place, but it's mainly behind the scenes.
The best of what R has to offer is a richness of packages (they are case sensitive, too!) containing functions. Think school algebra f(x) = y.
One or more arguments, x produces an output y, which can be as simple as a vector of numbers or may be a very structured object capturing a wealth of results of application of f.
That's not to say that there is no programming logic in R. For example function calls on a data frame can be chained using the %>% operator, similarly to the | pipe operator. And you may find yourself using ifelse() to make binary tests and return one result on success and failure.
Therefore, the first place to look when solving a problem with R is at the off-the-shelf functions that already do that.
If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: