Home > Net >  Issues with pivot longer in R
Issues with pivot longer in R

Time:03-31

this is a continuation of the below question. Sample data below

area <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware")
sept2020 <- c(.120,.125,.130,.110,.095,.045,.131,.029)
oct2020 <- c(.121,.129,.128,.119,.099,.041,.138,.028)
nov2020 <- c(.119,.128,.129,.118,.091,.048,.139,.185)

percent <- data.frame(area,sept2020,oct2020,nov2020)


library(dplyr)

percent2 <- percent %>%
mutate(across(-1, ~ rank(desc(.)), .names = "{.col}_rank"))


###first attempt
percent2 <- percent2 %>% filter (area == "Delaware") %>% pivot_longer(names_to = "rank", values_to = "count")

How to construct multiple columns at one time in R

So I have 6 columns. Sept2020, Oct2020, Nov2020, sept2020_rank, oct2020_rank, and nov2020_rank.

it is my assumption that to produce a ggplot plot where time is the x axis and rank is the y-axis, I have to first make it into long (example below) My first attempt is above. What would the cols item be in this case? I am looking to produce charts for individual states.

 area    date      rank
 Delware  sept2020    8
 Delaware   oct2020   8
 Delaware   nov2020   1

CodePudding user response:

you can try this and still keep the value column.

percent_res <- percent %>% pivot_longer(cols = 2:4, names_to = "date") %>% group_by(date) %>% mutate(rank = rank(value)) %>% ungroup()

  • Related