R tip #1: Don’t lose track of your outputs with ‘.Last.value’

Use .Last.value on R to keep data you forgot to save to a variable
tips
R
programming
RStudio
Author

Rafael Belokurows

Published

May 7, 2024

Greetings!

A quick R tip to get thins going:

If you’re a bit distracted like me and you sometimes forget to store your variables or outputs, having to run the same function more than once, like so:

Code
data.frame(a=c(1,2,3),b=c(4,5,6)) #oops, forgot to save it to a variable
  a b
1 1 4
2 2 5
3 3 6

Instead of doing this :

Code
df <- data.frame(a=c(1,2,3),b=c(4,5,6)) #there you go
df
  a b
1 1 4
2 2 5
3 3 6

Then I might have the solution for you. Base R has a function called .Last.value1 that recalls and lets you reuse your last console output (be it whatever it is).

This way, you can store it in a variable and do whatever you wanted to do with it in the first place!

You may ask me: Ok, but how will that save me time? Can’t I press the up arrow ⬆ and run the same code again? Yeah, sure, but what if you just ran a complex operation on a dataframe with many thousands of rows (or more)?
Using .Last.value lets you reuse the same data, this way you won’t waste time or computing power (which in a hosted environment could cost you some money).

This is the first of a series of tips to come, stay tuned for more!

Footnotes

  1. For more (but not whole more of a lot) on this function, there’s always R’s documentation.↩︎