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$
1
  • $\begingroup$ Be aware that the OP is NOT actually forming key value pairs from the data. They are taking the columns of their original data frame and listing them sequentially. This destroys any relationships that existed in the original data. Also, their table b does not actually represent key-value pairs because it contains non-unique keys, which goes against the logic of key-value pairs. $\endgroup$
    – abalter
    Dec 13, 2023 at 3:36

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 you have read our privacy policy.

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