官术网_书友最值得收藏!

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:

  1. Create the objects using the following code:
e <- as.Date("2016-09-05")
f <- as.POSIXct("2018-04-05")
  1. 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.

主站蜘蛛池模板: 江门市| 宁德市| 卫辉市| 安新县| 西贡区| 策勒县| 仁怀市| 中卫市| 永德县| 延津县| 垣曲县| 安乡县| 赤城县| 来宾市| 同江市| 屏东县| 淮阳县| 阳原县| 永兴县| 横山县| 湖口县| 河北省| 英德市| 财经| 邛崃市| 林西县| 沙田区| 繁峙县| 山东省| 威远县| 云安县| 孟村| 棋牌| 汉川市| 会东县| 景东| 浮山县| 栾城县| 五原县| 高尔夫| 陵川县|