Skip to main content

Data Frames in R

This tutorial takes course material from DataCamp's Introduction to R for Finance course and allows you to practice Data Frames.
Oct 2018  · 4 min read

 If you want to take our free Intro to R course, here is the link.

Accessing and subsetting data frames (1)

Even more often than with vectors, you are going to want to subset your data frame or access certain columns. Again, one of the ways to do this is to use [ ]. The notation is just like matrices! Here are some examples:

Select the first row: cash[1, ]

Select the first column: cash[ ,1]

Select the first column by name: cash[ ,"company"]

Instructions

  • Select the third row and second column of cash.
  • Select the fifth row of the "year" column of cash.

If that makes sense keep going to the next exercise! If not, here is an overview video.

Overview Video on Data Frames

Accessing and subsetting data frames (2)

As you might imagine, selecting a specific column from a data frame is a common manipulation. So common, in fact, that it was given its own shortcut, the $. The following return the same answer:

cash$cash_flow

[1] 1000 4000  550 1500 1100  750 6000

cash[,"cash_flow"]

[1] 1000 4000  550 1500 1100  750 6000

Useful right? Try it out!

Instructions

  • Select the "year" column from cash using $.
  • Select the "cash_flow" column from cash using $ and multiply it by 2.
  • You can delete a column by assigning it NULL. Run the code that deletes "company".
  • Now print out cash again.

R for Finance 2

Accessing and subsetting data frames (3)

Often, just simply selecting a column from a data frame is not all you want to do. What if you are only interested in the cash flows from company A? For more flexibility, try subset()!

subset(cash, company == "A")

  company cash_flow year
1       A      1000    1
2       A      4000    3
3       A       550    4

There are a few important things happening here:

  • The first argument you pass to subset() is the name of your data frame, cash.
  • Notice that you shouldn't put company in quotes!
  • The == is the equality operator. It tests to find where two things are equal, and returns a logical vector. There is a lot more to learn about these relational operators, and you can learn all about them in the second finance course, Intermediate R for Finance!

Instructions

  • Use subset() to select only the rows of cash corresponding to company B
  • Now subset() rows that have cash flows due in 1 year.

R for Finance 4

Adding new columns

In a perfect world, you could be 100% certain that you will receive all of your cash flows. But, since these are predictions about the future, there is always a chance that someone won't be able to pay! You decide to run some analysis about a worst case scenario where you only receive half of your expected cash flow. To save the worst case scenario for later analysis, you decide to add it as a new column to the data frame!

cash$half_cash <- cash$cash_flow * .5

cash

  company cash_flow year half_cash
1       A      1000    1       500
2       A      4000    3      2000
3       A       550    4       275
4       B      1500    1       750
5       B      1100    2       550
6       B       750    4       375
7       B      6000    5      3000

And that's it! Creating new columns in your data frame is as simple as assigning the new information to data_frame$new_column. Often, the newly created column is some transformation of existing columns, so the $ operator really comes in handy here!

Instructions

  • Create a new worst case scenario where you only receive 25% of your expected cash flow, add it to the data frame as quarter_cash.
  • What if it took twice as long (in terms of year) to receive your money? Add a new column double_year with this scenario.

R for Finance 4


If you want to learn more from this course, here is the link.

Introduction to Portfolio Analysis in R

Beginner
5 hours
30,547
Apply your finance and R skills to backtest, analyze, and optimize financial portfolios.
See DetailsRight Arrow
Start Course

Financial Trading in R

Beginner
5 hours
20,624
This course covers the basics of financial trading and how to use quantstrat to build signal-based trading strategies.

Intermediate Portfolio Analysis in R

Beginner
5 hours
10,087
Advance you R finance skills to backtest, analyze, and optimize financial portfolios.
See all coursesRight Arrow
Related
Data Science Concept Vector Image

How to Become a Data Scientist in 8 Steps

Find out everything you need to know about becoming a data scientist, and find out whether it’s the right career for you!
Jose Jorge Rodriguez Salgado's photo

Jose Jorge Rodriguez Salgado

12 min

Predicting FIFA World Cup Qatar 2022 Winners

Learn to use Elo ratings to quantify national soccer team performance, and see how the model can be used to predict the winner of FIFA World Cup Qatar 2022.

Arne Warnke

DC Data in Soccer Infographic.png

How Data Science is Changing Soccer

With the Fifa 2022 World Cup upon us, learn about the most widely used data science use-cases in soccer.
Richie Cotton's photo

Richie Cotton

Regular Expressions Cheat Sheet

Regular expressions (regex or regexp) are a pattern of characters that describe an amount of text. Regular expressions are one of the most widely used tools in natural language processing and allow you to supercharge common text data manipulation tasks. Use this cheat sheet as a handy reminder when working with regular expressions.
DataCamp Team's photo

DataCamp Team

ggplot2 Cheat Sheet

ggplot2 is considered to be one of the most robust data visualization packages in any programming language. Use this cheat sheet to guide your ggplot2 learning journey.
DataCamp Team's photo

DataCamp Team

A Guide to R Regular Expressions

Explore regular expressions in R, why they're important, the tools and functions to work with them, common regex patterns, and how to use them.
Elena Kosourova 's photo

Elena Kosourova

16 min

See MoreSee More