That's because you need to specify which environment you are clearing. By default, rm() clears the current environment, which is the environment inside the function. But you want to clear the global environment. So you need rm(list = ls(), envir = .GlobalEnv)