使用R中的as.date转换日期因子

时间:2016-10-16 11:17:01

标签: r

我正在尝试将数据列从因素转换为日期格式,但总会出现一些问题。原始日期列如下所示:

date
1/01/2008
1/01/2008
1/01/2008
1/01/2008
1/01/2008

查看前6行

head(PowerConsumption)

它表明:

$ Date: Factor w/ 729 levels "1/01/2007","1/01/2008",..: 189 189 189 189 189 189 189 189 189 189 ...
  1. 不太明白所有这些189意味着什么?

  2. 我的意思是更改因果日期类型。

  3. 应用此代码后:

    date <- as.Date(PowerConsumption$Date, format = "%d%m%Y")
    

    所有值都变为NA。任何人都可以指出什么是错的吗?

2 个答案:

答案 0 :(得分:3)

首先,所有189表示向量以该因子变量的第189级值开始。一个简化的例子:

> x <- factor(c("1/01/2007","1/01/2008","1/01/2007","1/01/2008"))
> str(x)
 Factor w/ 2 levels "1/01/2007","1/01/2008": 1 2 1 2

其次,当您想将该日期变量转换为日期格式时,您需要指定原始变量的正确格式(在指定格式参数时省略了/):

> as.Date(x, format="%d/%m/%Y")
[1] "2007-01-01" "2008-01-01" "2007-01-01" "2008-01-01"

与我在评论中所说的相反,这个因子变量不一定需要先用as.character转换为字符。

将因子值中心转换为日期的另一个选项是使用新anydate包中的anytime函数:

> library(anytime)
> anydate(x)
[1] "2007-01-01" "2008-01-01" "2007-01-01" "2008-01-01"

答案 1 :(得分:0)

当然,有一个<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container-fluid page-top"> <!-- Trigger the modal with a button --> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <div class="modal fade" id="myModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="form-horizontal" id="myForm" role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">My modal</h4> </div> <div class="modal-body"> <div class="form-group has-feedback"> <div class="col-lg-12"> <label class="control-label col-sm-3" for="tbTitle">Public Title:</label> <div class="input-group col-sm-5"> <input name="ctl00$cpMain$tbTitle" type="text" id="cpMain_tbTitle" class="form-control required" value="Basic Gold Program" /> </div> </div> </div> <div class="form-group has-feedback"> <div class="col-lg-12"> <label class="control-label col-sm-3" for="tbInternalTitle">Internal Title:</label> <div class="input-group col-sm-5"> <input name="ctl00$cpMain$tbInternalTitle" type="text" id="cpMain_tbInternalTitle" class="form-control required" value="BASEPLAN" /> </div> </div> </div> <div class="form-group has-feedback"> <div class="col-lg-12"> <label class="control-label col-sm-3" for="tbPrice">Monthly Price:</label> <div class="input-group col-sm-5"> <input name="ctl00$cpMain$tbPrice" type="text" id="cpMain_tbPrice" class="form-control required" value="$75.00" /> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div>解决方案:

lubridate