0

I have data in long format and am trying to spread data to long format group_by an identifier. I have tried the solution posted here and and receive this error message Error in -x : invalid argument to unary operator. I have also tried the solution posted here.

My dataset looks like this;

iden<-c(rep(1:25, 2), rep(26:50, 2))
group<-c(rep(5, 25), rep(20, 25), rep(-18, 25), rep(-80, 25))
value<-sample(100:5000, 100, replace=TRUE)
df<-data.frame(iden, group, value)

Please help me figure out how to get the data in wide format without duplicate identifiers (see attched image here for expected output).

For image of @Ronak Shah's answer see image here

Dustin
  • 183
  • 7
  • Can you share the code that you have tried? What is the expected output that you are looking for? – Ronak Shah Jun 17 '20 at 02:24
  • 2
    `df %>% group_by(group) %>% mutate(iden = row_number()) %>% spread(group, value)`. `spread` has been retired and replaced by `pivot_wider` instead. – Ronak Shah Jun 17 '20 at 02:43
  • @Ronak Shah. I tried; ```df %>% group_by(iden) %>% mutate(id = row_number()) %>% select(-unique) %>% spread(group, value) %>% select(-id)``` and ```df %>% group_by(group) %>% mutate(ind = row_number()) %>% spread(group, value) %>% select(iden, group, value)```. Your code almost works! I'm looking for there to be 50 observations (rows) with values in two of the new columns per row. Thanks so much for helping out! – Dustin Jun 17 '20 at 05:45
  • Can you update your post to show first few rows of expected output? – Ronak Shah Jun 17 '20 at 06:51
  • @Ronak Shah. I have added an image of expected output. I tried the solution in the post my question is similar to, but it does not use ```spread``` (or ```pivot_wider```), and it did not work for me. Thank you helping me. – Dustin Jun 17 '20 at 19:30
  • Sorry but I think my answer gives you the same expected output as shown in the image. It has unique `iden` as one column and 4 columns with 5, 20, -18, -80. – Ronak Shah Jun 17 '20 at 23:49
  • @Ronak Shah. If I run this code; ```Ronak<-df %>% group_by(group) %>% mutate(iden = row_number()) %>% spread(group, value)``` then, ```head(Ronak)```, I get the image added to my edited question. So there is data being incorrectly spread to values that don't exist. I hope this helps. – Dustin Jun 18 '20 at 00:24

0 Answers0