简体   繁体   English

R-如何将一个空的POSIXct列添加到已经存在的data.frame / tibble中?

[英]R - How can I add an empty POSIXct column to a data.frame / tibble which already exists?

I can initialize a data frame with a POSIXct column with code like this: 我可以使用以下代码用POSIXct列初始化数据帧:

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

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. 但是,如果我尝试将空的POSIXct列添加到已经存在的data.frame或tibble中,则该列将转换为数字类型/类。

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

Is there a method to overcome this problem? 有没有解决这个问题的方法?

would this work for you (most doing what eipi10 suggest in his comment ) 会为您工作吗(大多数做eipi10在他的评论中建议)

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 ...

or maybe 或者可能

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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将data.frame中两个POSIXct列之一的值分配给新的POSIXct列? - How can I assign the value from one of two POSIXct columns in a data.frame to a new POSIXct column? 如何将data.frame中的列从POSIXct转换为R中的日期 - How to convert a column in a data.frame from POSIXct to date in R 如何对 R 中的 data.frame 或 tibble 列中的 NA 值的总数求和,并按月和年对它们进行分组 - How can I sum the totals of NA values in a data.frame or tibble column in R and group them by Month and Year 如何在现有data.frame中添加其他列,这些列在data.frame中已有的一个特定列上对齐? - How can I add additional columns to an existing data.frame, that are aligned on one specific column already in the data.frame? 是否有一个R包具有data.frame的通用类,其中列可以是数组(或者我如何定义这样的类)? - Is there an R package with a generalized class of data.frame in which a column can be an array (or how do I define such a class)? R - 将 Data.frame 元素转换为单列 tibble() - R - Transform Data.frame elements into a single column tibble() 如何将data.frame中的列从字符转换为POSIXct? - How to convert a column in data.frame from characters to POSIXct? 如何使用 POSIXct 类型的列初始化 data.frame? - How to initialize data.frame with column of type POSIXct? 将数据添加到空r data.frame - Add data to empty r data.frame 如何在R中将列表列表转换为整洁的小标题或data.frame - How to convert list of list into tidy tibble or data.frame in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM