0

Here is the base code example im working on, this code generates data similar to the data i am working on.


library(dplyr)

library(tidyr)

stocks <- data.frame(
  time = as.Date('2009-01-01'),
  price = rnorm(4, 0, 1)
)

this makes a data.frame of the type

    
   time         price
1 2009-01-01    1.79731518
2 2009-01-01   -0.43010058
3 2009-01-01    0.22578283
4 2009-01-01   -0.09225956

This data is the product of

stocks <- stock_db %>% group_by(time) %>% summarise(ceiling(quantile(price, probs = c(.5, .90, .95, 1))))

here is what i want to create

   time         price_1       price_2        price_3      price_3
1 2009-01-01    1.79731518    -0.43010058    0.22578283   -0.09225956

i have tried every combination of %>% mutate(...) and %>% spread(...) that i can think of

the main issue im having with spread() is that it seems like the correct function for this but im getting errors when i apply it to the data frame

ERROR

Error: Must extract column with a single valid subscript.
x Subscript `var` has the wrong type `data.frame<
  time : date
  price: double
>`.
i It must be numeric or character.

i tried passing both of the columns to

stocks$time <- as.numeric(stocks$time)
stocks$price <- as.numeric(stocks$price)

but this doesn't change to error

my end goal is to scale this to a larger data.frame with 4 values for each date of a year

   time         price_1       price_2        price_3      price_3
1 2009-01-01    1.79731518    -0.43010058    0.22578283   -0.09225956
1 2009-01-02    1.79731518    -0.43010058    0.22578283   -0.09225956
1 2009-01-03    1.79731518    -0.43010058    0.22578283   -0.09225956
1 2009-01-04    1.79731518    -0.43010058    0.22578283   -0.09225956
..etc...

  • 1
    See [reshape data from long to wide in R](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format). – Rui Barradas Oct 01 '20 at 13:30
  • Try `stocks2 <- stocks %>% mutate(id=paste0('price',1:n())) %>% pivot_wider(names_from = id,values_from=price)` – Duck Oct 01 '20 at 13:30

0 Answers0