Split it
Often, you will have data for multiple groups together in one data frame. The cash
data frame was an example of this back in Chapter 3. There were cash_flow
and year
columns for two groups (companies A and B). What if you wanted to split up this data frame into two separate data frames divided by company
? In the next exercise, you will explore why you might want to do this, but first let's explore how to make this happen using the split()
function.
Create a grouping
to split on, and use split()
to create a list of two data frames.
grouping <- cash$company
split_cash <- split(cash, grouping)
split_cash
$A
company cash_flow year
1 A 1000 1
2 A 4000 3
3 A 550 4
$B
company cash_flow year
4 B 1500 1
5 B 1100 2
6 B 750 4
7 B 6000 5
To get your original data frame back, use unsplit(split_cash, grouping)
.
This exercise is part of the course
Introduction to R for Finance
Exercise instructions
- The
cash
data frame is available in your workspace. - Create a new
grouping
from theyear
column. - Use
split()
to splitcash
into a list of 5 data frames separated byyear
. Assign this tosplit_cash
. - Print
split_cash
. - Use
unsplit()
to combine the data frames again. Assign this tooriginal_cash
. - Print
original_cash
to compare to the firstcash
data frame.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define grouping from year
grouping <-
# Split cash on your new grouping
split_cash <-
# Look at your split_cash list
# Unsplit split_cash to get the original data back.
original_cash <-
# Print original_cash