0

I need to extract the year from vote_data and save it into another column to finally sort the dataframe by year. R dataframe

Anyone with an idea? If it is possible to sort it without extracting, that would be even better. Already tried sorting, but did not find out how to sort only by year when the cell contains the whole date.

  • It's . asier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Please [do not post code or data in images](https://meta.stackoverflow.com/q/285551/2372064) – MrFlick Nov 08 '22 at 15:57

3 Answers3

1

We could do

library(dplyr)
library(lubridate)
df1 <- df1 %>% 
    mutate(year = year(ymd(vote_date))) %>%
    arrange(year)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You are looking for arrange() from the dplyr package:

df = data.frame(
       vote_id = 1:3,
       vote_date = c("1975-04-25","1976-04-25","1974-04-25")
)

dplyr::arrange(df, df$vote_date)
dplyr::arrange(df, desc(df$vote_date)) # Descendent
Laura
  • 24
  • 1
-1

Check out the lubridate package, I believe it has the functions you're looking for!

Holly
  • 11
  • 2
  • 2
    Please avoid [link only answers](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259). Try to include enough information to be able to help the user should the link ever disappear. – MrFlick Nov 08 '22 at 15:59