# multiple gather with 4 columns resulting "together"

## Question:

Hi,

I have the following situation:

I have a data frame with several columns, a group of them I want to transform into key value. So far so good, but there are 2 groups and they can't sort of repeat themselves. Like, it's a group of 3 and a group of 3

``````NOME      A1   A2    A3    B1    B2    B3
batata     6   4     7      2    1      1
maçã       9   4     8      1    2      0
``````

I did the gather 2 times, once for A1 A2 A3 and once for B1 B2 B3. The problem is that the resulting row number is 2*3*3 = 18, as it takes a result from A and makes a row for each result from B

``````NOME    keyA    valueA    keyB    valueB
batata   A1       6        B1       2
batata   A1       6        B2       1
batata   A1       6        B3       1
maçã     A1       9        B1       2
maçã     A1       9        B2       1
maçã     A1       9        B3       1
``````

……….(same process with A2 and A3)

What I need is for each value of A1, I have only key B1, of A2 only B2, etc. So:

``````NOME    keyA    valueA    keyB    valueB
batata   A1       6        B1       2
batata   A2       4        B2       1
batata   A3       7        B3       1
maçã     A1       9        B1       1
maçã     A2       4        B2       2
maçã     A3       8        B3       0
``````

Only 6 lines

Can anyone help me? XD

Here's a solution:

``````library(tidyverse)

x <- data.frame(
NOME = c("batata", "maça"),
A1 = c(6, 9),
A2 = c(4, 4),
A3 = c(7, 8),
B1 = c(2, 1),
B2 = c(1, 2),
B3 = c(1, 0)
)

x %>%
gather(keyA, valueA, starts_with("A")) %>%
gather(keyB, valueB, starts_with("B")) %>%
filter(parse_number(keyA) == parse_number(keyB))
``````

The `parse_number` function takes just the `parse_number` part of a variable, so you can use it to compare the columns keyA and keyB to get only what you need.

Scroll to Top