WebR Charlie Data Example

Creating Variable Objects

Basic Syntax

The first thing to note is that in the code chunks below you will see text in green preceded by a #. These are called comments and R will skip any lines these lines and not treat them as code to run. These are very useful for writing notes to yourself outlining different sections in your code and explaining what your code does.

You may think “why would I take the extra time to explain every line?”, but your future self will thank you. You might think the code seems obvious when you are writing it, but months later when you want to reuse that script it might look like gibberish. (Trust me, I know this first hand.) So, adding comments is always good to do.

The following code has comments and uses another common R symbol, the assign symbol or <-. Instead of using an equals sign to set values, R uses <-. We call this assigning, so x <- 5 can be read as “x is assigned the value of 5”.

(Sidenote: Most things do work with an equals sign, but some things don’t, so when you want to make a new variable object, using <- instead of = is good practice.)

When you create an object you will see it appear in your Variable Environment in the top right. If you don’t see it there, then you didn’t successfully store the value as an object we can use later.

We can use objects according to whatever their value is, meaning if they are numbers we can use the object names for math. Add a line to the following that creates the object y, then run the code to see the output.

One thing to note is that if you store a value it won’t automatically be printed to the console. If we run the following code, you shouldn’t see any output to the console, but you will see the object z appear in the Variable Environment.

What would you need to do if you wanted to print z to the console?

Variable objects can be many things

Objects don’t have to be a single number, they can be a variety of things. In the following code, we store the word ‘cactus’ as a string in the object plant and a vector (a list of numbers) as the object num_list. Note here that to tell R we want the list of numbers as a vector we use a function: c(). That function combines all the numbers into one vector.

Try doing some math with these new variables and see what works and what doesn’t.

You can also store an entire spreadsheet of data as a variable object. That is what we do when we load data.