Intro to R Top



1. Use Text Editor

You can type in command directly in the command window (lower left), but for any analysis of data, you should use write a script in text editor (top left), and save your script.

R has built-in Editor

R-studio has built-in editor, which can send command to the console by Ctrl+R. You can send it line by line, or by region.

You can use any text editor you like

Alternative to above is to use external text editor like Notepad. If you use the external editor, you can copy and paste your code to console.

2. Comment Your Code

In R , everyting that comes after # in each line will be ignored. This is to be used as a commenting tool. For each code that you are not too familiar with, you should insert brief comment, to remind you what that line of code does.

In R, there is no support for comment multiple lines at once. So if you are putting long comment, you must put # at the beginning of each line.

If you are using R-studio, you can comment block with Control + Shift + C.

Try to keep your comment short and to the point.

3. Keep Your Code, Not Workspace

You can save your script by clicking on the save bottun, or going to FILE -> SAVE. Default extention is .R, but since script is a text file, you can use any other extention such as .txt.

You should keep all the codes you write for future references. In many parts of data analysis, you will be applying same methodology for different datasets. If you have well documented code saved in organized folder, and can quickly go back to the codes you used before, that will save you tons of time.

In general, it is better to save the code that can quickly reproduce the result from the original code, than to save the workspace (R will ask you when you colose) and try to come back later. Chances are that you will not be sure exactly where you were in your code.

4. Small Coding Tips


Up arrow to recall command

On R console, You can press Up arrow key to recall all the past commands.

You can use ; to conbine two lines of code into one

For example,

Does the same thing as

If you donโ€™t put ;, R will give you an error. This should not be used too often, but can be used to save space if you have short repetitive codes. <!- endofyank->