本文介绍了R-如何将一个空的POSIXct列添加到已经存在的data.frame / tibble中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码用POSIXct列初始化数据帧:

I can initialize a data frame with a POSIXct column with code like this:

df <- data.frame(a=numeric(), b=character(), c=as.POSIXct(character()))

但是,如果我尝试将一个空的POSIXct列添加到已经存在的data.frame或tibble中,则该列将转换为数字类型/类。

However, if I try to add an empty POSIXct column to a data.frame or tibble which already exists, the column is transformed to numeric type/class.

> df <- tibble("Index"=numeric(10))
> df[,"date"] <- as.POSIXct(character())
> df[,"date"] %>% pull %>% class()
[1] "numeric

是否有一种方法可以解决此问题?

Is there a method to overcome this problem?

推荐答案

将为您完成这项工作(大多数情况下是做什么的) eipi10在)

would this work for you (most doing what eipi10 suggest in his comment)

library(tibble) # install.packages(c("dplyr"), dependencies = TRUE)
df <- tibble(a = 1:3, b = letters[a], c = as.POSIXct(NA))

df 
#> # A tibble: 3 x 3
#>       a     b      c
#>   <int> <chr> <dttm>
#> 1     1     a     NA
#> 2     2     b     NA
#> 3     3     c     NA

str(df)
#> Classes ‘tbl_df’, ‘tbl’ and 'data.frame':
#>    3 obs. of  3 variables:
#> $ a: int  1 2 3
#> $ b: chr  "a" "b" "c"
#> $ c: POSIXct, format: NA NA ...

或者也许

df <- tibble(a = numeric(), b = character(), c = as.POSIXct(NA))
str(df)
#> Classes ‘tbl_df’, ‘tbl’ and 'data.frame':
#>   0 obs. of  3 variables:
#> $ a: num 
#> $ b: chr 
#> $ c:Classes 'POSIXct', 'POSIXt'  num(0) 

这篇关于R-如何将一个空的POSIXct列添加到已经存在的data.frame / tibble中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 20:12