as.posixct在应用于数据框中的元素时返回数字,而不是日期和时间 [英] as.posixct when applied for an element in the data frame returns a number instead of date and time

查看:154
本文介绍了as.posixct在应用于数据框中的元素时返回数字,而不是日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是现有数据:

I有2列数据。第一列的每一行都具有数据,而第二列的仅某些行具有数据(其他为空白)。我想借助as.POSIXct()转换数据格式。对于第一列,我使用以下代码(我将数据框命名为 mrkt):

I have 2 columns of data. Each row of the first column has data whereas only certain rows of the second column has data (others being blank). I want to convert the format of the data with the help of as.POSIXct(). For the first column I used the following code (I named the data frame as 'mrkt'):

mrkt[1]<-lapply(mrkt[1],as.POSIXct)

这在转换现有数据以正确的格式
对于第二列,上面的代码将无效,因为as.POSIXct()无法处理值。所以我改写了一个循环:

This worked well in terms of converting the existing data to the right format For the second column the above code won't work as the as.POSIXct() cannot address "" values. So I wrote a loop instead:

for (i in 1:dim(mrkt[2])[1]){
   if (!as.character(mrkt[[2]][i])==""){
       mrkt$open_time[i]<-as.POSIXct(mrkt$open_time[i])
    }
 }

但是,这给了我奇怪的输出形式一个号码。我该如何避免呢?输出为:

However this is giving me weird outputs in the form of a number. How can I avoid that? Here is the output:

推荐答案

这是由于从 POSIXct 到数字的隐式类型转换所致。这仅在循环中发生,因为向量具有分配的类型,并且如果分配了单个值,则将值强制转换为该类型。当替换整个向量时,将使用正确的类型创建一个新向量。

This is due to implicit typecasting from POSIXct to numeric. This only happens in the loop because the vector has an assigned type and values are casted to this type if single values are assigned. When the whole vector is replaced a new vector is created with the right type.

最简单的解决方案是使用 as.POSIXct(strptime(mrkt $ open_time,format = yourformat)),使用正确定义的格式,请参阅?strptime 了解格式。这是矢量化的,并且strptime可以正确处理空字符串(返回 NA )。

The simplest solution is to use as.POSIXct(strptime(mrkt$open_time, format=yourformat)), with a correctly defined format, see ?strptime for the formats. This is vectorized, and strptime handles empty Strings correctly (returning NA).

这篇关于as.posixct在应用于数据框中的元素时返回数字,而不是日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆