【问题标题】:R - How can I add an empty POSIXct column to a data.frame / tibble which already exists?R - 如何将一个空的 POSIXct 列添加到已经存在的 data.frame / tibble 中?
【发布时间】:2018-02-21 12:03:34
【问题描述】:

我可以用这样的代码初始化一个带有 POSIXct 列的数据框:

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

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

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

有没有办法解决这个问题?

【问题讨论】:

  • as.POSIXct(rep(NA,10)) ?你不可能有一个真正的“空”POSIXct我不认为
  • dat[,"date"] &lt;- as.POSIXct(NA) 也可以。

标签: r dataframe posixct tidyverse


【解决方案1】:

这对你有用吗(大多数都在做 eipi10 在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) 

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 2020-02-19
    • 2021-12-07
    • 2011-03-04
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多