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

Time:05-10

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

CodePudding user response:

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)
  • Related