R is a vectorized language so using a loop for this kind of thing is not a good idea, you can learn how to transform your data as you described by reading this free ebook.
https://r4ds.had.co.nz/transform.html
If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.