3
$\begingroup$

If I have data like this in R:

> a = data.frame(a = c(1, 2),
               b = c(3, 4))
> a
  a b
1 1 3
2 2 4

but I would like to have it like this:

> b = data.frame(k = c("a", "a", "b", "b"),
+                v = c(1, 2, 3, 4))
> b
  k v
1 a 1
2 a 2
3 b 3
4 b 4

How can I convert the data this way?

$\endgroup$

2 Answers 2

2
$\begingroup$

This is a simple gather() using package tidyr:

> library(tidyr)
> 
> gather(a, key = "k", value = "v")
  k v
1 a 1
2 a 2
3 b 3
4 b 4
$\endgroup$
2
$\begingroup$

You can alternatively use the melt() function from the reshape2 package

> library(reshape2)
> 
> melt(a, variable.name="k", value.name="v")
No id variables; using all as measure variables
  k v
1 a 1
2 a 2
3 b 3
4 b 4

Hope this is insightful!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.