D. Studer
D. Studer

Reputation: 1875

data transformation (gather?)

I have the following tibble:

~id, ~a, ~b, ~c, ~d,
1, 10, 20, 33, 42,
2, 30, 20, 32, 42,
3, 34, 24, 35, 32,
4, 32, 24, 35, 25,
5, 22, 14, 35, 36,
...
)

But I'd rather like to have it in that form (only columns 'a' and 'b')

~id, ~aOrB, ~value
1, a, 10,
1, b, 20,
2, a, 30,
2, b, 20,
3, a, 34,
3, b, 24,
...

Does anyone know how to get it? I think it can be done using "gather()", but I didnt manage to get it working:

newTable <- oldTable %>% gather(a, b, value='cases')

Upvotes: 0

Views: 49

Answers (1)

Phil
Phil

Reputation: 8107

Use ?gather to read more on how to use the gather function.

library(dplyr)
library(tidyr)

oldTable %>% select(-c, -d) %>% gather(key = aOrB, value = value, -id)

EDIT: If you want to keep c and d, but not stacked:

    oldTable %>% gather(key = aOrB, value = value, -id, -c, -d)

If you want to keep c and d, and stacked along with a and b:

    oldTable %>% gather(key = aOrBOrCOrd, value = value, -id)

Upvotes: 1

Related Questions