簡體   English   中英

根據 r 中現有列的值創建具有條件 label 的新列

[英]Create new column with a conditional label based on value of an existing column in r

我有一個 2 列 df,兩個字符,但一列實際上是一個時間 (h:m) 列。 我想根據現有時間列的值是上午 8 點到下午 6 點還是下午 6 點到 8 點,創建一個名為“DAY.NIGHT”的新列。

我嘗試使用 hms package 將現有時間列轉換為 hms 類型,我覺得它可能與我附加的其他包有關,因為有時我的代碼可以正常工作,但隨后它會隨機停止工作,我無法讓它再次工作。

有沒有人可以在不使用 hms package 的情況下實現我想要的替代方法?

編輯1:真實的形式我只是再次運行它(沒有改變任何東西)並且它隨機工作。 昨天也發生了同樣的事情。 因此,如果有人在沒有 hms package 的情況下有另一種方法來實現這一點,那就太好了。

編輯 2下面是我傾向於得到的錯誤。 奇怪的是它有時會起作用,但大多數時候我都會收到這個錯誤:

<error/dplyr:::mutate_error>
Error in `mutate()`:
! Problem while computing `DAY.NIGHT = ifelse(...)`.
ℹ The error occurred in row 1.
Caused by error:
! All arguments must be numeric or NA
---
Backtrace:
  1. time_agg %>% rowwise() %>% ...
  8. hms::hms(TIME)
  9. hms:::check_args(args)
 10. base::stop("All arguments must be numeric or NA", call. = FALSE)

這是問題所在的腳本的摘錄:

library(tidyverse) 
library(ggplot2)
library(lubridate)
library(scales) 
library(viridis) 
library(hrbrthemes) 
library(e1071) 
library(rstatix)
library(GGally)
library(hms)

df_time <- data.frame(
  REGION = rep(c("NSW", "VIC", "QLD", "SA", "TAS"), each=50),
  TIME = rep(c("00:00", "08:00", "12:00", "21:00", "22:00"), each=10))
)

df_time$TIME <- as_hms(df_time$TIME)

day.night <- df_time %>%
  rowwise() %>%
  mutate('DAY.NIGHT'= ifelse(
    hms(TIME) > hms("8:00:00") & 
      hms(TIME) < hms("18:00:00"), "DAY", "NIGHT"))

我在第一行df_time$TIME <- as_hms(df_time$TIME)中得到了您的錯誤。 我認為這是因為as_hms期望有小時、分鍾和秒,但您的輸入沒有秒。 讓我們粘貼幾秒鍾:

## add :00 seconds for no error
df_time$TIME <- as_hms(paste0(df_time$TIME, ":00"))

一旦TIME列已經是hms class,您就不想再對其使用hms() 我們希望使用as_hms()而不是hms (如果您將 H、M 和 S 作為單獨的 arguments 提供,hms hms()看起來是合適的。)

day.night <- df_time %>%
  mutate('DAY.NIGHT'= ifelse(
    TIME > as_hms("8:00:00") & 
      TIME < as_hms("18:00:00"), "DAY", "NIGHT"))
## no warnings, no errors, should run consistently if your inputs are consistent
day.night
#     REGION     TIME DAY.NIGHT
# 1      NSW 00:00:00     NIGHT
# 2      NSW 00:00:00     NIGHT
# 3      NSW 00:00:00     NIGHT
# 4      NSW 00:00:00     NIGHT
# 5      NSW 00:00:00     NIGHT
# 6      NSW 00:00:00     NIGHT
# ...

暫無
暫無

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

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