Home > Mobile >  Is it possible to replace just 0s in a column with just non zeros from another column within a using
Is it possible to replace just 0s in a column with just non zeros from another column within a using

Time:10-21

Just a general question I have 3 columns in R that of only of importance two num columns and 1 date column. I want to use mutate to replace only 0s within sum_prec from within 2018-08-11 to 2019-09-16 with est_precp numbers is this possible or not in R using mutate or another code or package.

$ sum_prec     : num [1:29679] 0 0 0 0 0 0 0 0 0 0 ...
$ date         : Date[1:29679], format: "2014-09-11" "2014-09-11" ...
$ est_precp    : num [1:29679] 0 0 0 0 0 0 0 0 0 0 ...

CodePudding user response:

The data.table way:

# assuming your data.frame is called 'df'
library(data.table)
setDT(df)

# find relevant rows and change the sum_prec to est_precp
df[ date > as.Date("2018-08-11") & 
    date < as.Date("2019-09-16") & 
    sum_prec == 0, 
    sum_prec := est_precp]

CodePudding user response:

I think this is what you want, but as DanY said, it's easier if you provide an MCVE.

library(magrittr)

# Example dataset
example_data <- tibble::tribble(
  ~sum_prec, ~date, ~est_precp,
  0, "2014-09-11", 1,
  0, "2018-08-11", 2
)

# Range of dates you want
dates_of_interest <- seq(as.Date("2018-08-11"), as.Date("2019-09-16"), by = "day")

# Replace values in `sum_prec` column with values from `est_precp` if 
# `sum_prec` is zero and if `date` is within range
new_data <- example_data %>% 
  dplyr::mutate(
    sum_prec = dplyr::if_else(
      condition = sum_prec == 0 & as.Date(date) %in% dates_of_interest,
      true = est_precp,
      false = sum_prec
    )
  )
  •  Tags:  
  • r
  • Related