0

From a dataframe like this:

dframe = data.frame(data = c(1), error = c(3))

How can we melt the data aiming to have the col names as values.

Here an example of expected output

 dframe_ex = data.frame(id=c("data","error"), num=c(1,3))
 dframe_ex
     id num
1  data   1
2 error   3
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Elr Mant
  • 507
  • 1
  • 4
  • 14
  • 1
    Possible duplicate of [Reshape from wide to long format/structure](https://stackoverflow.com/questions/28261492/reshape-from-wide-to-long-format-structure) – NelsonGon Feb 19 '19 at 01:10

3 Answers3

2

use this

library(tidyr)
dframe %>%
  gather(id, num)

output is

     id num
1  data   1
2 error   3
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Stephan
  • 2,056
  • 1
  • 9
  • 20
2

This is a case for base R's stack

stack(dframe)
#  values   ind
#1      1  data
#2      3 error
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

you can use melt in reshape2 :

library(reshape2)
dframe_ex <- melt(dframe)

> print(dframe_ex)
  variable value
1     data     1
2    error     3

If you want to have the col names you specified then:

library(tidyverse)
dframe_ex <- melt(dframe) %>% 
  rename(id = variable, num = value)
nycrefugee
  • 1,629
  • 1
  • 10
  • 23