Loops are control flow statemtents that repeat the same code for a certain number of iterations. So, if you want to do the same thing over and over again, a loop might be exactly what you need. Loops often have a bad reputation among coders because they can be relatively slow and can also be confusing, especially compared to functionals (ex. apply() functions).1 But I can’t deny it, I really love loops.
Changing my data from wide to long format, or vice versa was somehow always a headache. Eventhough I did this a lot, it just DID NOT stick in my head for the longest time. Everytime, I had to google it, and then work through at least 5 failed attempts before I’d get it. Therefore, this totally warrants a blog post, ya? I recently started using tidyr’s spread() and gather() functions to do this, and I find them a lot more intuitive than the alternatives (the tidyverse strikes again), so that’s what I’ll focus on here.
Honestly, I am not even sure what to title this post. I can’t remember what I googled that eventually took me to a website that answered my question, but I think it was something a long the lines of “re-level embedded list R” maybe? Anyways… the nifty trick that I eventually came accross that does exactly what I want is probably worth a blog post… Let’s say that I have a list of utilization distribution objects (each calculated using locations collected during a different year) embedded in a list of of different individuals (so, the list structure is Individual > Year > Object).
By far the most common data wranging question that I get asked by friends and colleagues is “Without having to use R, how do I pull values from one table into another, based on matching shared values in another column?” The answer is the almighty INDEX MATCH function in Excel. Actually, although I call it “the INDEX MATCH function,” it’s a MATCH function nested inside an INDEX function (basically, the MATCH function tells the INDEX function which value to pull).