Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn a column with repeating observations into a column for each observation in R

My data currently looks like in the photo below. What I would like is a single column for all unique values of the "permno" variable with the following values of "ret_excess" as rows.
So there would be a "10145" column, a "10516" and so on.
The Permno variable is a stock identifier with ret_excess being monthly returns. There is a date variable that says the year/month of the observation, which I have removed but can add if needed 🙂

Thanks in advance!

How my current data look

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It sounds like you want to pivot the table from long to wide. For that to make sense there need to be one or more columns that uniquely identifies each observation.

Assuming the date column is a unique identifier for each permno + ret_excess pair, you can do:

library(tidyr)
df %>%
  pivot_wider(id_cols = date, names_from = permno, values_from = ret_excess)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading