In this article, we will study what R language and uses of R language. Further, we will move to learn that how we can extract the year from the date in the R programming language along with the example code.
What is R language?
R is a programming language and free software that possesses an extensive catalog of the statistical and graphical method. It includes many machine learning algorithms, statistical inferences, linear regression, etc. Most of the R language is written in R language but some of them are written in C and C++ for heavy computation.
Data analysis in R is done in a series of steps like programming, transforming, discovering, modeling, and communicate the result. R programming has a large number of packages available which helps analysis of data extremely easily with R. The packages like the reader, dplyr is capable of transforming messy data into a structured form in the R language. Therefore, R provides exemplary support for data wrangling. R programming is mainly known as the lingua franca of statistics. The meaning of this is that R programming is mostly used for developing statistical tools.
Extracting Year from Data in R using the format()
The following code shows how to extract the year from a date using the format() function combine with the Y% argument.
#create data frame df <- data.frame(date=c("02/10/2021", "03/07/2020" , "14/03/2021"), sales=c(21, 36, 38)) #view data frame df date sales 1 02/10/2021 21 2 03/07/2020 36 3 14/03/2021 38 #create new variable that contains year df$year <- format(as.Date(df$date, format="%d/%m/%Y"),"%Y")
Output:
df
date sales year
1 02/10/2021 21 2021
2 03/07/2020 36 2020
3 14/03/2021 38 2021
Extracting Year from Data Using Lubridate in R
We can also extract the year from the date using the function from the lubridate package. See the following example:
library(lubridate) #create data frame df <- data.frame(date=c("02/10/2021", "03/07/2020" , "14/03/2021"), sales=c(21, 36, 38)) #view data frame df date sales 1 02/01/2021 21 2 03/07/2020 36 3 14/03/2021 38 #create new variable that contains year df$year <- year(mdy(df$date))
Output:
df
date sales year
1 02/01/2021 21 2021
2 03/07/2020 36 2020
3 14/03/2021 38 2021
By this, we can extract the year from the date in R programming language using the format() or lubridate function.
Conclusion
So, in this article, we studied what is R language and its uses. Also, we studied two different ways to extract the year from the data in the R programming language, its example, and its output.