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

  • 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:

  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.

主站蜘蛛池模板: 普安县| 芒康县| 驻马店市| 洛阳市| 吉木萨尔县| 红原县| 英吉沙县| 铜山县| 无为县| 西华县| 九龙坡区| 改则县| 德钦县| 乌海市| 方山县| 刚察县| 镇宁| 区。| 延川县| 区。| 江油市| 社旗县| 宁城县| 盐津县| 乐清市| 南投市| 松溪县| 西吉县| 封开县| 阳城县| 高清| 遂平县| 拉孜县| 凤城市| 株洲县| 阜平县| 鄂州市| 新龙县| 通州区| 南昌县| 四川省|