- 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.
- GNU-Linux Rapid Embedded Programming
- Deep Learning Quick Reference
- Excel 2007函數與公式自學寶典
- Spark編程基礎(Scala版)
- Dreamweaver CS3網頁制作融會貫通
- 工業機器人工程應用虛擬仿真教程:MotoSim EG-VRC
- Implementing Splunk 7(Third Edition)
- 云原生架構進階實戰
- 大數據驅動的機械裝備智能運維理論及應用
- 空間機械臂建模、規劃與控制
- 液壓機智能故障診斷方法集成技術
- PowerMill 2020五軸數控加工編程應用實例
- 智慧未來
- DynamoDB Applied Design Patterns
- Flash CS5二維動畫設計與制作