我有一個資料框,Date_Time_GMT_3其中有一列標有日期/時間。我使用該Date_Time_GMT_3列創建了另一個資料框,其中包含 3 個額外的列,這些列具有month year和day分隔。這個新的資料框如下所示:
df = structure(list(Date_Time_GMT_3 = structure(list(sec = c(0, 0,
0, 0, 0, 0), min = c(0L, 0L, 0L, 0L, 0L, 0L), hour = c(8L, 8L,
8L, 8L, 8L, 8L), mday = c(1L, 1L, 1L, 1L, 1L, 1L), mon = c(5L,
5L, 5L, 5L, 5L, 5L), year = c(121L, 121L, 121L, 121L, 121L, 121L
), wday = c(2L, 2L, 2L, 2L, 2L, 2L), yday = c(151L, 151L, 151L,
151L, 151L, 151L), isdst = c(0L, 0L, 0L, 0L, 0L, 0L), zone = c("EST",
"EST", "EST", "EST", "EST", "EST"), gmtoff = c(NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_)), tzone = "EST", class = c("POSIXlt",
"POSIXt")), name = c("X20676880_X3WR_AIR_Stationary", "X20819740_X3WR_U_Stationary",
"X20819740_X3WR_S_Stationary", "X21092860_X3WR_U_Compare", "X20676883_13WR_U_Stationary",
"X20676883_13WR_S_Stationary"), value = c(11.431, 11.625, NA,
NA, 10.651, NA), month = c(6, 6, 6, 6, 6, 6), year = c(2021,
2021, 2021, 2021, 2021, 2021), day = c(1L, 1L, 1L, 1L, 1L, 1L
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
我用來從列中獲取month day和year列的代碼Date_Time_GMT_3如下所示
mutate(month = lubridate::month(Date_Time_GMT_3),
year = lubridate::year(Date_Time_GMT_3),
day = lubridate::day(Date_Time_GMT_3))
有沒有辦法使用該lubridate函式來獲取時間列。我試過這行代碼
mutate(month = lubridate::month(Date_Time_GMT_3),
year = lubridate::year(Date_Time_GMT_3),
day = lubridate::day(Date_Time_GMT_3),
#New LINE OF CODE
time = lubridate::hms(Date_Time_GMT_3))
當我使用新的代碼行時,出現此錯誤
Warning message:
Problem with `mutate()` column `TIME`.
i `TIME = lubridate::hms(Date_Time_GMT_3)`.
i Some strings failed to parse, or all strings are NAs
任何想法如何使它作業?
uj5u.com熱心網友回復:
它不起作用,因為hms()只需要三元組中的數字,您在時間之前有一個日期,因此您需要先洗掉該部分,然后再將其傳遞給hms(). 我已經使用了,substr因為所有日期必須具有相同的格式,在這種情況下為 YYYY-MM-DD,因此請保留從第 11 個字符開始的所有內容。
lubridate::hms(substr(df$Date_Time_GMT_3, 11, nchar(df$Date_Time_GMT_3)))
[1] "8H 0M 0S" "8H 0M 0S" "8H 0M 0S" "8H 0M 0S" "8H 0M 0S" "8H 0M 0S"
在 dplyr
df %>%
mutate(hms = lubridate::hms(substr(Date_Time_GMT_3, 11, nchar(Date_Time_GMT_3))))
# A tibble: 6 x 7
Date_Time_GMT_3 name value month year day hms
<dttm> <chr> <dbl> <dbl> <dbl> <int> <Period>
1 2021-06-01 08:00:00 X20676880_X3WR_AIR_Station~ 11.4 6 2021 1 8H 0M 0S
2 2021-06-01 08:00:00 X20819740_X3WR_U_Stationary 11.6 6 2021 1 8H 0M 0S
3 2021-06-01 08:00:00 X20819740_X3WR_S_Stationary NA 6 2021 1 8H 0M 0S
4 2021-06-01 08:00:00 X21092860_X3WR_U_Compare NA 6 2021 1 8H 0M 0S
5 2021-06-01 08:00:00 X20676883_13WR_U_Stationary 10.7 6 2021 1 8H 0M 0S
6 2021-06-01 08:00:00 X20676883_13WR_S_Stationary NA 6 2021 1 8H 0M 0S
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407500.html
標籤:
下一篇:一年中的最后一周歸因于下一年
