from character to year in r

To convert a character variable to a year format in R, you can use the as.Date() or ymd() function from the lubridate package.

Here's an example using as.Date():

main.r
# Sample character date
char_date <- "2022-01-01"

# Convert character to year format using as.Date()
year_date <- as.Date(char_date, format = "%Y-%m-%d")
year <- format(year_date, "%Y")

# Print the year
print(year)
217 chars
10 lines

Output:

main.r
[1] "2022"
11 chars
2 lines

And here's an example using ymd():

main.r
# Load lubridate package
library(lubridate)

# Sample character date
char_date <- "2022-01-01"

# Convert character to year format using ymd()
year_date <- ymd(char_date)
year <- format(year_date, "%Y")

# Print the year
print(year)
233 chars
13 lines

Output:

main.r
[1] "2022"
11 chars
2 lines

gistlibby LogSnag