0

I want to reshape a very simple dataframe and can't find the way to do that

I tried this solution: Transposing data frames and all related solutions, with no luck

I have a tidy dataframe who looks like this:

    df<-rbind(c('a','x1'),c('a','x2'),c('a','x3'),
    c('b','x6'),c('b','x7'))
    colnames(df)<-c('var','val')

And tried

library(dplyr)
library(tidyr)
df %>%
  gather(var, val, 2:ncol(df)) %>%
  spread_(names(data)[1], "val")

I want a dataframe that looks like:

a   x1   x2   x3  
b   x6   x7   NA

But I get this error

Error: Each row of output must be identified by a unique combination of keys
Sotos
  • 51,121
  • 6
  • 32
  • 66
Oscar Benitez
  • 255
  • 3
  • 13
  • FYI, your `df` is a matrix not a data frame – Sotos Jul 04 '19 at 13:38
  • @Sotos: I tried to simplify here the actual dataframe I have. Sorry for my ignorance, but convert the data frame I have to a matrix would simplify the resolution of the problem? – Oscar Benitez Jul 04 '19 at 13:45
  • 2
    No, it needs to be a data.frame. No problem though. I got what you were asking. I was just looking for a duplicate target as this looks like a question that has been asked before :) – Sotos Jul 04 '19 at 13:49

1 Answers1

-1

We need a group by sequence after converting to data.frame (the OP's example is a matrix)

library(dplyr)
library(tidyr)
library(stringr)
df %>% 
   as.data.frame %>%
   group_by(var) %>% 
   mutate(rn = str_c("col", row_number()))  %>% 
   spread(rn, val)
# A tibble: 2 x 4
# Groups:   var [2]
#  var   col1  col2  col3 
#  <fct> <fct> <fct> <fct>
#1 a     x1    x2    x3   
#2 b     x6    x7    <NA> 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 7
    The reason for my downvote here is because I think your answering dupes actually creates a lot of noise in the site thus not helping. A clear dupe was added (OP said he has a data frame but put here matrix for simplicity-or so he thought) and your reopening is not justified in my oppinion, hence the downvote. The other link you share, not my downvotes. Thanks. – Sotos Jul 04 '19 at 14:08
  • It is a matrix, and it had to go through couple of steps, and note that your sequence creation is for the row index in that dupe and note for the column – akrun Jul 04 '19 at 14:09
  • Ok. Your opinion. Lets agree to disagree :) Have a nice day – Sotos Jul 04 '19 at 14:10