Manipulate date format

Viewed 40

While merging datasets, there are different kinds of date format that disable to join these datasets.

the values of date as a year unit is what I needed, like 2004, 2005, 1996, 1987.

but they have different format int, I_chr, dbl.

I used various methods to manipulate but failed. Does anyone know how to solve this problem?

the data sample 1 is

glimpse(ARTD_data_reshaped)
Rows: 9,606
Columns: 12

$ country         chr "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afg~
$ year            I chr 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1~
$ combined_regime chr "Monarchy", "Monarchy", "Monarchy", "Monarchy", "Monarchy", "Mon~
$ kailitz_tri     int 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0~

the data sample 2 is

glimpse(FH_data_2_reshaped_new)
Rows: 621
Columns: 3

$ country   chr "Abkhazia", "Abkhazia", "Abkhazia", "Afghanistan", "Afghanistan", "Afg~
$ year      int 2003, 2004, 2005, 2003, 2004, 2005, 2003, 2004, 2005, 2003, 2004, 2005~
$ pr_rating chr "9", "9", "9", "8", "9", "13", "26", "26", "26", "11", "11", "10", "39~

1. method 1

FH_data_2_reshaped_new <- read.csv(file = "FH_data_2_reshaped.csv") %>% 
select(country, year, pr_rating) %>%
as.POSIXct(year)

Error in as.POSIXct.default(., year) : 不知如何將 '.' 轉換成 “POSIXct” 類別

2. method 2

FH_data_2_reshaped_new <- read.csv(file = "FH_data_2_reshaped.csv") %>% 
select(country, year, pr_rating) %>%
mutate(year = lubridate::year(year))

Error: Problem with mutate() column year. i year = lubridate::year(year). x 'origin' 一定得給值

1 Answers

There are multiple ways of doing this. One of the best ways to do it is using as.Date from base R.

Note: Assuming the name of the data frame is df.

The code will look like this:

df$year <- as.Date(df$year, format = "%Y")

This will convert the year column from the data frame to class date. Although it will append the current date and month to the year. i.e the year value will look be converted to a format yyyy-mm-dd where mm and dd are current month and date.

If you do not want the month and date part you can do it using lubridate library.

library(lubridate)
df$year <- as.Date(as.character(df$year), format = "%Y")
df$year <- year(df$year)

It will give you the only year part. But, remember that it will be of class numeric and not Date.

Related