It's not exactly clear from your post what is going wrong.
If you are using RStudio or Rgui to run R, then the code you posted can be saved from the editor window into a new script file which has the extension .R or .r (e.g. "my_script.R").
If you want to save a copy of all the objects created by your R session, then you can use the specific
save.image() function (see below) to write a file named ".RData". Also, R will ask if you want to save the ".RData" file at the end of an R session (i.e. when you Exit) unless you have changed the default settings for this action. But beware, as the ".RData" file is automatically loaded the next time R is started with this directory, and this can lead to unexpected results and behaviour.
The ".RData" file starts with a dot and in some OSs it is "hidden" and not shown by default when looking at directory listings. In File Explorer on Windows you have to tick 'Hidden Items' and 'File name extensions' in the View pull-down menu.
x <- c(18,21,22,22,23,23,23,24,25,25,25,26,27,27,27,28,29,33,38,52)
main="Sections 2.1.1 & 2.1.2 ",
# These are the objects in your current R session
# Save all the current R objects to a file on disk called ".RData"
# in the current default directory.
# Check the directory used and whether the file now exists.
Note that the histogram itself is NOT stored since it has not be assigned to an object, whereas the data have been assigned to x.
Hope this helps.