简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM