I need to extract the year from vote_data and save it into another column to finally sort the dataframe by year.
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.
CodePudding user response:
We could do
library(dplyr)
library(lubridate)
df1 <- df1 %>%
mutate(year = year(ymd(vote_date))) %>%
arrange(year)
CodePudding user response:
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
CodePudding user response:
Check out the lubridate package, I believe it has the functions you're looking for!