更改 R data.frame 的某些月份的变量值?

Change value of variables for certain months of an R data.frame?

我想在 Month =< 2 & Month >= 11 时将 ObsSim 的值更改为 -1.23。看起来很简单,但我没有提出任何解决方案。

library(tidyverse)
library(lubridate)

set.seed(123)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2003-12-31"), by = "day"),
                  Ob = runif(1095,1,5), Sim = runif(1095,1,5)) %>% 
        separate(Date, into = c("Year", "Month", "Day"))

首先将 Month 转换为数字,以便您可以比较这些值。接下来,当 Month <= 2 OR >= 11.

时,您可以将 ObSim 列的值更改为常量
DF$Month <- as.numeric(DF$Month)
DF[DF$Month <= 2 |  DF$Month >= 11, c('Ob', 'Sim')] <- -1.23

或使用%in%

DF[DF$Month %in% c(1,2,11,12), c('Ob', 'Sim')] <- -1.23

如果你想使用 dplyr 你可以这样做:

library(dplyr)
DF <- DF %>% 
       mutate(across(c(Ob, Sim), ~replace(., Month %in% c(1, 2, 11, 12), -1.23)))

有几个问题需要解决。一种是将月份和日期设为数字,这样您就可以在它们上面使用等于和 greater/less 比运算符。一旦你有了它,使用 case_when 来执行你的替换逻辑。第三个问题是 =< 不是有效函数。你应该使用 <=。最后,Month <= 2 & Month >= 11 将 return 0 行,因为对于两个子句,没有行可以 return TRUE。我在示例中使用了不同的标准。

library(tidyverse)
library(lubridate)

set.seed(123)

DF <- tibble(Date = seq(ymd("2001-01-01"), to = ymd("2003-12-31"), by = "day"),
             Ob = runif(1095,1,5),
             Sim = runif(1095,1,5)) %>% 
  mutate(Year = year(Date),
         Month = month(Date),
         Day = mday(Date))

DF %>% 
  mutate(Ob = case_when(Month <= 10 & Month >= 6 ~ -1.23,
                        TRUE ~ Ob),
         Sim = case_when(Month <= 10 & Month >= 6 ~ -1.23,
                        TRUE ~ Sim)) %>% 
  filter(Month <= 10 & Month >= 6)

# A tibble: 6 x 6
  Date          Ob   Sim  Year Month   Day
  <date>     <dbl> <dbl> <dbl> <dbl> <int>
1 2001-06-01 -1.23 -1.23  2001     6     1
2 2001-06-02 -1.23 -1.23  2001     6     2
3 2001-06-03 -1.23 -1.23  2001     6     3
4 2001-06-04 -1.23 -1.23  2001     6     4
5 2001-06-05 -1.23 -1.23  2001     6     5
6 2001-06-06 -1.23 -1.23  2001     6     6