[英]How can I assign the value from one of two POSIXct columns in a data.frame to a new POSIXct column?
[英]R - How can I add an empty POSIXct column to a data.frame / tibble which already exists?
我可以使用以下代碼用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
有沒有解決這個問題的方法?
會為您工作嗎(大多數做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 ...
或者可能
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.