Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

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

Is there a method to overcome this problem?

like image 611
Francisco Yirá Avatar asked Oct 17 '25 09:10

Francisco Yirá


1 Answers

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

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) 
like image 191
Eric Fail Avatar answered Oct 19 '25 01:10

Eric Fail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!