- R Programming Fundamentals
- Kaelen Medeiros
- 343字
- 2021-07-23 16:58:20
Dates
Dates are a special type of data in R, and are distinct from the date types POSIXct and POSIXlt, which represent calendar dates and times in more formal ways.
Let's create and check the class() and typeof() of different date objects in R. Follow these steps:
- Create the objects using the following code:
e <- as.Date("2016-09-05")
f <- as.POSIXct("2018-04-05")
- Check the class and type of each by using class() and typeof(), respectively, as follows:
class(e)
typeof(e)
class(f)
typeof(f)
Output: The preceding code provides the following output:

One nice thing about R is that we can change objects from one type to another using the as.*() function family. If we have a variable, var, which currently has the value of 5, but as a character string, we can cast it to numeric data type using as.numeric() and to an integer using as.integer(), which the following code demonstrates:
#char to numeric, integer
var <- "5"
var_num <- as.numeric(var)
class(var_num)
typeof(var_num)
var_int <- as.integer(var)
class(var_int)
typeof(var_int).
Conversely, we can go the other way and cast the var_num and var_int variables back to the character data type using as.character(). The following code demonstrates this:
#numeric, integer to char
var <- 5
#numeric to char
var_char <- as.character(var_num)
class(var_char)
typeof(var_char)
#int to char
var_char2 <- as.character(var_int)
class(var_char2)
typeof(var_char2)
A character string can be converted into a Date, but it does need to be in the format Year-Month-Day (Y-M-D) so that you can use the as.Date() function, as shown in the following code:
#char to date
date <- "18-03-29"
Date <- as.Date(date)
class(Date)
typeof(Date)
There are formatting requirements for dates for them to save correctly. For example, the following code will not work:
date2 <- as.Date("03-29-18")
It will throw the following error:
Error in charToDate(x) : character string is not in a standard unambiguous format
It will be important to understand variable types throughout a data science project. It would be very difficult to both clean and summarize data if you're unsure of its type. In Chapter 3, Data Management, we'll also introduce another variable type: factors.
- AWS:Security Best Practices on AWS
- Mastering Salesforce CRM Administration
- 21天學通C++
- 小型電動機實用設(shè)計手冊
- 大型數(shù)據(jù)庫管理系統(tǒng)技術(shù)、應(yīng)用與實例分析:SQL Server 2005
- Cloudera Administration Handbook
- 精通數(shù)據(jù)科學算法
- Visual Basic.NET程序設(shè)計
- Docker on Amazon Web Services
- 網(wǎng)絡(luò)管理工具實用詳解
- Mastering GitLab 12
- 菜鳥起飛電腦組裝·維護與故障排查
- JSP通用范例開發(fā)金典
- 軟測之魂
- Flash CS3動畫制作融會貫通