我有以下 df
,其中 Date
列有一整年的小时标记:
Date TD RN D.RN Press Temp G.Temp. Rad
1 2018-01-01 00:00:00 154.0535 9.035156 1.416667 950.7833 7.000000 60.16667 11.27000
2 2018-01-01 01:00:00 154.5793 9.663900 1.896667 951.2000 6.766667 59.16667 11.23000
3 2018-01-01 01:59:59 154.5793 7.523438 2.591667 951.0000 6.066667 65.16667 11.23500
4 2018-01-01 02:59:59 154.0535 7.994792 2.993333 951.1833 5.733333 64.00000 11.16833
5 2018-01-01 03:59:59 154.4041 6.797526 3.150000 951.4833 5.766667 57.83333 11.13500
6 2018-01-01 04:59:59 155.1051 12.009766 3.823333 951.0833 5.216667 61.33333 11.22167
我想添加一个因子列“季度”,根据“日期”指示每个季度。 据我所知,我可以通过以下方式做到这一点:
Radiation$Quarter<-cut(Radiation$Date, breaks = "quarters", labels = c("Q1", "Q2", "Q3", "Q4"))
但我还想添加一个因子列“Day/Night”,指示是白天还是黑夜,具有:
白天 → 上午 8 点 - 晚上 8 点
晚上 → 晚上 8 点 - 早上 8 点
似乎 cut()
函数无法指示时间范围。
答案 0 :(得分:2)
您可以在从时间中提取小时后使用 ifelse
/case_when
语句。
library(dplyr)
library(lubridate)
df %>%
mutate(hour = hour(Date),
label = case_when(hour >= 8 & hour <= 19 ~ 'Day',
TRUE ~ 'Night'))
在基础 R 中:
df$hour = as.integer(format(df$Date, '%H'))
transform(df, label = ifelse(hour >= 8 & hour <= 19, 'Day', 'Night'))
答案 1 :(得分:1)
我们也可以
<img src='' id="edit_image" width="180px;" height="120" class="mt-2">
<p>Old image</p>