在R中使用带间隔的ifelse()作为条件表达式

问题描述 投票:1回答:3

我的数据集如下所示:

> head(GLM_df)
# A tibble: 6 x 9
# Groups:   hour [6]
   hour Feeding Foraging Standing ID    Area     Feeding_Foraging Feeding_Standing Standing_Foraging
  <int>   <dbl>    <dbl>    <dbl> <chr> <chr>               <dbl>            <dbl>             <dbl>
1     0    3.5      23.3     1    41361 Seronera             26.8             4.5               24.3
2     1    2.71     24.2     1    41361 Seronera             26.9             3.71              25.2
3     2    2.5      24.3     2    41361 Seronera             26.8             4.5               26.3
4     3    6.88     18.7     3.89 41361 Seronera             25.5            10.8               22.6
5     4    7.5      17.6     3.67 41361 Seronera             25.1            11.2               21.3
6     5    7.22     19.6     2.45 41361 Seronera             26.8             9.67              22.1

而且我只想添加一个Day_Night列,它将在DayGLM_df$hour之间的6中使用18,否则将使用Night

我尝试使用下面的表达式,但我收到以下错误:

> GLM_df$Day_Night<-ifelse(GLM_df$hour==(6:18),Day,Night)
Error in ifelse(GLM_df$hour == (6:18), Day, Night) : 
  object 'Day' not found
In addition: Warning message:
In GLM_df$hour == (6:18) :
  longer object length is not a multiple of shorter object length

任何帮助表示赞赏!

r if-statement
3个回答
0
投票

使用data.table

GLM_df <- as.data.table(GLM_df)
GLM_df[hour %in% c(6:18), Day_Night:="Day"]
GLM_df[!hour %in% c(6:18), Day_Night:="Night"]

2
投票

尝试使用findInterval()

GLM_df$Day_Night <- ifelse(findInterval(GLM_df$hour, c(6, 18),
                           rightmost.closed=TRUE) == 1L, 'Day', 'Night')

2
投票

只是:

library(tidyverse)
data %>% mutate(day_night = ifelse( hour %in% 6:18, "day", "night"))

要么:

data$day_night <- ifelse( data$hour %in% 6:18, "day", "night")
© www.soinside.com 2019 - 2024. All rights reserved.