Transposing a dataframe
You will sometimes be given a format that contains data that is arranged vertically and you want to flip it so that the variables are arranged horizontally. You will also hear this referred to as long format versus wide format. Most predictive analytics packages are set up to use long format, but there are often cases in which you want to switch rows with columns. Perhaps data is being input as a set of key pairs and you want to be able to map them to features for an individual entity. Also, this may be necessary with some time series data in which the data which comes in as long format needs to be reformatted so that the time periods appear horizontally.
Here is a data frame that consists of sales for each member for each month in the first quarter. We will use the text='
option of the read.table()
function to read table data that we have pasted directly into the code. For example, this is from data that has been pasted directly from an Excel spreadsheet:
sales_vertical...