Data Frames and Adding Stuff – R

Creating a simple data frame with two columns.

column 1 is called var1 and column 2 is called var2

first we need to populate them (add data)

var1 <- c(2,4,6,8)
var2 <- c(1,3,4,7)

we use the c() when we have a whole bunch of stuff we want to use together.

Now we turn this into a data frame called dfVar

dfVar <- data.frame(var1,var2)

That simple.

So if we type


we should get

 var1  var2
   2     1
   4     3
   6     4
   8     7

The rows and columns are counted in that way, first row, then column.

So row 4 column 2, or


will return 7

But if you only write one value in the [ ], then that will represent the column number, so that


will return all the values in column 2.

If you want all values in row 2 you will have to write


The "," means you’re telling R that you’re talking about a specific row, but not a specific column, which is why you leave it empty.

Adding both columns can be done by


to create a new column (which we will call v1v2) with the result of the addition


Finally we can do a cumulative sum of column 2, and place it in column 4, like this:


we should end up with this

   var1 var2 v1v2  var2.1
1    2    1    3      1
2    4    3    7      4
3    6    4   10      8
4    8    7   15     15

Lazy Man’s Copy+Paste

dfVar <- data.frame(var1,var2)

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s