0
votes

I'm trying to spread a two column dataset into multiple columns. Here is a similar dataframe.

dummydf<- data.frame(LnPD=rnorm(25,0.6,3),K=rep(x,5))

All I want to do is reshape the data so each column is an appropriate factors (i.e. there should be 5 columns each for A:E) with corresponding figures. I thought this would do it but it keeps asking for column names:

  dummy %>% 
  group_by(K) %>%
  mutate(group_now = 1:n())
  spread(K,LnPD)

I'm sure it's a simple fix but I can't get my head around it. The other error it gave me was something related with duplicate identifiers, although that was with my own dataset not the above.

Thanks in advance.

1
What is x in the dummydf definition?alistaire
you are missing a pipe (%>%) after your mutate call and you call dummy instead of dummydf. When I correct those issues and replace K=rep(x, 5) in your data.frame() call with K=rep(c(1, 2, 3, 4, 5),5) the code works for metbradley
I'll give it a go. Sorry the missing pipe and dummy only happened when I wrote script in here. btw the x is x<-factor(LETTERS[1:5])Dasr
Thanks guys. All good. Managed to get it sorted. Not sure what it was but seems to work after I restarted Rstudio!Dasr

1 Answers

1
votes

As per tbradley's comment, this works for me:

library(tidyverse)

x <- factor(LETTERS[1:5])
dummydf <- data.frame(LnPD=rnorm(25,0.6,3),K=rep(x,5))

dummydf %>% 
  group_by(K) %>%
  mutate(group_now = 1:n()) %>% 
  spread(K, LnPD)

#> # A tibble: 5 x 6
#>   group_now      A     B     C       D     E
#> *     <int>  <dbl> <dbl> <dbl>   <dbl> <dbl>
#> 1         1 -0.330  4.25 2.83   1.64    1.88
#> 2         2  1.56   2.51 0.348 -6.30    1.34
#> 3         3  0.589 -5.91 2.60   9.25    2.26
#> 4         4  3.47   4.83 2.89  -0.778   2.98
#> 5         5  2.22  -3.36 2.13  -0.0230  1.19