andre macedo costa
andre macedo costa

Reputation: 13

Is there a way to transform a table this way in R?

Please help, I want to transform a table in R this way bellow, from this:

ID Product 1 Product 2
1 0 10
2 20 30
3 50 0

To this:

ID Product Amount
1 2 10
2 1 20
2 2 30
3 1 50

I am finding it difficult, hope you can help me with this

Upvotes: 0

Views: 70

Answers (1)

dyrland
dyrland

Reputation: 648

You can use pivot_longer()!

library(tidyverse)
#first, make the data
df <- tibble(ID          = c(1,2,3),
             `Product 1` = c(0, 20, 50),
             `Product 2` = c(10, 30 , 0)
)
#then transform it
df_trans <- df %>%
  pivot_longer(cols = !ID,              #all columns except the ID column
               names_to = "Product",
               names_prefix = "Product" #removes the "Product" prefix
               values_to = "Amount"
  ) %>%
  filter(Amount > 0) #you don't want 0s, from your sample?

Upvotes: 1

Related Questions