Clean Up Memory in R
Last Updated :
01 May, 2022
In this R article, we will discuss how to clean up memory with its working example in the R programming language. Let’s first discuss removing objects from our workspace first.
rm() function in R Language is used to delete objects from the workspace. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.
Syntax: rm(x)
Parameters:
x: Object name
Example:
In this example, we are creating some data and remove from the workspace.
R
vec <- c (1, 2, 3, 4)
vec
list1 = list ( "Number" = c (1, 2, 3),
"Characters" = c ( "a" , "b" , "c" ))
list1
mat <- matrix ( c (1:9), 3, 3)
mat
rm (list1)
ls ()
|
Output:
[1] 1 2 3 4
$Number
[1] 1 2 3
$Characters
[1] "a" "b" "c"
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[1] "mat" "vec"
Using gc() function to remove all objects that are used from memory:
gc() is used to remove all objects that are used from memory.
Syntax:
gc(reset = TRUE)
reset is an optional parameter.
It will return the maximum memory used in Mb.
Example:
In this example, we are creating some data and remove from memory.
R
vec <- c (1, 2, 3, 4)
vec
list1 = list ( "Number" = c (1, 2, 3),
"Characters" = c ( "a" , "b" , "c" ))
list1
mat <- matrix ( c (1:9), 3, 3)
mat
gc ()
|
Output:
[1] 1 2 3 4
$Number
[1] 1 2 3
$Characters
[1] "a" "b" "c"
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 271233 14.5 654180 35 448093 24.0
Vcells 458584 3.5 8388608 64 1770431 13.6
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...