-2

I'm looking for a solution to create a pivot_longer from a pivot_wide (screenshot). In the end the goal is to receive a ggplot.

My first attempt was the direct way:

 hi %>% mutate(nr=row_number())%>% 
                ggplot(hi, aes(x=row.names, y=nr(1)))
                +geom_bar(stat="identity") 

#-> error

screenshot link: [1]: https://i.stack.imgur.com/JZKvp.jpg

The months (2018M...) I tried to have on the left, the related values (255...)on the right. On the top new row numbers, my thought was that's the best way to create a ggplot after.

Do someone have any ideas? Thanks a lot for your help!

  • 1
    Please don’t use images of data as they cannot be used without a lot of unnecessary effort. Questions should be reproducible. Check out stack overflow guidance [mre] and [ask]. Include a minimal dataset in the form of an object for example if a data frame as `df <- data.frame(…)` where … are your variables and values or use `dput(head(df))`. [Good overview on asking questions](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Peter Dec 10 '21 at 19:30

1 Answers1

0

It’s not really clear to me what you want, but here’s a possible start to convert to long format and plot. I also remove the ‘2018M’ from the name because it will be easier to plot. The result will be one bar plot of the twelve values.

library(tidyverse)
set.seed(1)
df <- data.frame(matrix(rnorm(12, mean = 100, sd = 20), nrow=1))
names(df) <- paste0("2018M", 1:12)

df <-
  df %>%
  pivot_longer(starts_with("2018M")) %>%
  mutate(name = as.numeric(gsub(".*M", "", name)))

ggplot(data = df, aes(x = name, y = value)) +
  geom_bar(stat = "identity")

TrainingPizza
  • 1,090
  • 3
  • 12