簡體   English   中英

使用 R 組合日期和小時

[英]Combining date and hour using R

我的數據框如下所示:

         clvs     fecha   hour    pml pml_ene pml_per pml_cng
1   07APD-230 2016-01-27    1 310.95  325.20  -14.25    0.00
2   07APD-230 2016-01-27    2 310.79  324.06  -13.27    0.00
3   07APD-230 2016-01-27    3 310.73  323.35  -12.63    0.00
4   07APD-230 2016-01-27    4 310.80  323.06  -12.25    0.00
5   07APD-230 2016-01-27    5 311.27  323.68  -12.41    0.00
6   07APD-230 2016-01-27    6 311.26  324.71  -13.44    0.00
7   07APD-230 2016-01-27    7 311.16  325.18  -14.01    0.00
8   07APD-230 2016-01-27    8 310.26  321.02  -10.75    0.00
9   07APD-230 2016-01-27    9 315.36  329.49  -14.13    0.00
10  07APD-230 2016-01-27   10 315.60  332.26  -16.66    0.00
11  07APD-230 2016-01-27   11 317.48  333.61  -16.13    0.00
12  07APD-230 2016-01-27   12 317.77  334.59  -16.82    0.00

我想要的是結合 fecha 和 hour 以“2016-01-27 01:00”格式獲得一列“日期”

我試過

BCA17$date <- as.Date(with(BCA17, paste(fecha, hour,sep="")), "%Y%m%d %H")

但我得到了充滿 NA 的“約會”

如果要轉換為 POSIXct 對象,可以使用as.POSIXct

transform(df, datetime = as.POSIXct(paste(fecha, hour), format = '%Y-%m-%d %H'))

#       clvs      fecha hour    pml pml_ene pml_per pml_cng            datetime
#1  07APD-230 2016-01-27    1 310.95  325.20  -14.25       0 2016-01-27 01:00:00
#2  07APD-230 2016-01-27    2 310.79  324.06  -13.27       0 2016-01-27 02:00:00
#3  07APD-230 2016-01-27    3 310.73  323.35  -12.63       0 2016-01-27 03:00:00
#4  07APD-230 2016-01-27    4 310.80  323.06  -12.25       0 2016-01-27 04:00:00
#5  07APD-230 2016-01-27    5 311.27  323.68  -12.41       0 2016-01-27 05:00:00
#6  07APD-230 2016-01-27    6 311.26  324.71  -13.44       0 2016-01-27 06:00:00
#7  07APD-230 2016-01-27    7 311.16  325.18  -14.01       0 2016-01-27 07:00:00
#...

或者要使用特定格式的數據format

transform(df, datetime = format(as.POSIXct(paste(fecha, hour), format = '%F %H'), '%F %H:%M'))
#        clvs      fecha hour    pml pml_ene pml_per pml_cng         datetime
#1  07APD-230 2016-01-27    1 310.95  325.20  -14.25       0 2016-01-27 01:00
#2  07APD-230 2016-01-27    2 310.79  324.06  -13.27       0 2016-01-27 02:00
#3  07APD-230 2016-01-27    3 310.73  323.35  -12.63       0 2016-01-27 03:00
#4  07APD-230 2016-01-27    4 310.80  323.06  -12.25       0 2016-01-27 04:00
#5  07APD-230 2016-01-27    5 311.27  323.68  -12.41       0 2016-01-27 05:00
#...

我們可以使用 tidyverse

library(dplyr)
library(stringr)
library(lubridate)
df %>%
    mutate(datetime = ymd_h(str_c(fecha, hour, sep = " ")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM