Conversion from a wide to a long format

image

Hi, I would like to go from wide format in the picture where I have 8 columns, to a long format where I end up with three columns (one with prices, one with quantities, and one column with an ID number, and one column with years i guess). p0, p1 etc represents individual products, so I need some sort of an ID number to distinguish the different products.

Do anyone have any suggestions on how to do this?

Here is the data:

p0 <- c(2.97, 2.96, 2.93, 3.03)
p1 <- c(3.64, 3.50, 3.36, 3.42)
p2 <- c(6.75, 6.71, 6.67, 6.73)
p3 <- c(3.37, 3.29, 3.37, 3.37)

q0 <- c(15, 25, 32, 33)
q1 <- c(44, 79, 65, 90)
q2 <- c(49, 41, 35, 53)
q3 <- c(35, 59, 30, 31)

Hi @trymkok! Without any data I can't provide anything more specific, but you could take a look at the function pivot_longer() from the tidyr package.

Here you have the data:

p0 <- c(2.97, 2.96, 2.93, 3.03)
p1 <- c(3.64, 3.50, 3.36, 3.42)
p2 <- c(6.75, 6.71, 6.67, 6.73)
p3 <- c(3.37, 3.29, 3.37, 3.37)

q0 <- c(15, 25, 32, 33)
q1 <- c(44, 79, 65, 90)
q2 <- c(49, 41, 35, 53)
q3 <- c(35, 59, 30, 31)

Thanks! Something like this?

library(tidyr)

p0 <- c(2.97, 2.96, 2.93, 3.03)
p1 <- c(3.64, 3.50, 3.36, 3.42)
p2 <- c(6.75, 6.71, 6.67, 6.73)
p3 <- c(3.37, 3.29, 3.37, 3.37)

q0 <- c(15, 25, 32, 33)
q1 <- c(44, 79, 65, 90)
q2 <- c(49, 41, 35, 53)
q3 <- c(35, 59, 30, 31)

year <- 2015:2018

data.frame(year, p0, p1, p2, p3, q0, q1, q2, q3) %>% 
  pivot_longer(cols = -year,
               names_to = c(".value", "set"),
               names_pattern = "(.)(.)")

Nice, thanks! Have a wonderful day!

1 Like

@trymkok would you mind marking my post as solution so we can close this issue? Have a nice day too! :smile:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.