1

There is a dataframe, example

df<-data.frame("x"=c(10,15,20,25),
          "y1"=c(0,1,0,1),
          "y2"=c(1,1,1,0))

I am trying to restructure it vertically to the form

df1<-data.frame("x"=c(10,10,15,15,20,20,25,25),
            "y"=c(0,1,1,1,0,1,1,0))

so that the columns y1 and y2 changes to a single column y.

I tried using the reshape package and the melt function, as follows

library(reshape)
df1 <- melt(df, y=c("x","y1","y2"))

But it fails to work and reports the following error message:

Using  as id variables

I have also followed similar problems (e.g. How do I flip rows and columns in R) but these do not fit into the specifics of my problem. Any help on this is well appreciated.

T Richard
  • 525
  • 2
  • 9
  • `tidyr::pivot_longer(df, cols = -x)` – Ronak Shah Oct 09 '19 at 00:57
  • @RonakShah thanks! tidyr::pivot_longer reports the following error: "Error: 'pivot_longer' is not an exported object from 'namespace:tidyr'". Please, how can I fix this problem. – T Richard Oct 09 '19 at 01:20
  • 1
    by installing latest version of `tidyr` or in previous version it is `gather`, `tidyr::gather(df, key, value, -x)` – Ronak Shah Oct 09 '19 at 01:22
  • @RonakShah gather works but it does not provide the output as expected. Instead of x=c(10,10,15,15,20,20,25,25) it gives x=c(10,15,20,25,10,15,20,25). – T Richard Oct 09 '19 at 02:00
  • The expected output is already there you just need to sort the output. `df %>% gather(key, value, -x) %>% select(-key) %>% arrange(x) ` is the complete code for your expected output. – Ronak Shah Oct 09 '19 at 02:03

0 Answers0