I have been working on a data analysis project for several hours and my R environment is getting quite crowded. I’m looking for a quick command to list all the variables I’ve created so far. Is there also a way to see more detailed information about these variables, like their class or memory size, directly in the console without having to check the environment pane in RStudio every time?
3 answers
The most basic and widely used command to list your variables in R is ls(). When you run this in the console, it returns a character vector containing the names of all objects currently stored in your global environment. If you prefer, objects() performs the exact same function. For a more detailed overview, I highly recommend using ls.str(), which not only lists the names but also displays a brief summary of the structure of each object. This is incredibly helpful when you have multiple data frames and want to quickly verify their dimensions or column types without running str() on each one individually.
Is there a way to filter the results of the ls() command? For example, can I list only the variables that start with a specific prefix like 'data_'?
If you want to see how much memory each variable is taking up, you should use the object.size() function or the lsos() helper function often found in community snippets.
I agree with Nancy. Monitoring memory is crucial when working with "Big Data." I often use sort(sapply(ls(), function(x) object.size(get(x))), decreasing = TRUE) to find the largest objects in my environment. Kimberly, this helps you identify which variables you should remove using rm() to free up RAM.