1

I would like to make some condition or something like that so that whenever we have NA or empty values ​​in PV, the values ​​are the same as coef values, that is, for 2021-06-30, ABC, for example, the value of the PV will be 1, which is the same coef value for that date/category.

Test <- structure(list(id=c("1","1","2","1"), date = structure(c(18808, 18808, 18809, 18810
), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
coef = c(4, 1, 6, 1),PV = c(1, "", NA, "")), row.names = c(NA, 4L), class = "data.frame")
    
    > Test
  id       date Category coef   PV
1  1 2021-06-30      FDE    4    1
2  1 2021-06-30      ABC    1     
3  2 2021-07-01      FDE    6 <NA>
4  1 2021-07-02      ABC    1 
  • 1
    Does this answer your question? [How to implement coalesce efficiently in R](https://stackoverflow.com/questions/19253820/how-to-implement-coalesce-efficiently-in-r). 1) Convert all empty strings to `NA` in column PV. 2) Use any of the `coalesce` functions posted following that link. – ekoam Jan 10 '22 at 00:40
  • Thanks for reply, but notice that for 2021-06-30, FDE is 1 in PV colunmn. This one remains the same, the problem is the others, is there any difference for that? –  Jan 10 '22 at 00:58
  • That's exactly the use case of `coalesce` function. It only updates a value at a certain position when it is `NA`; non-`NA` values are left unchanged. Try perhaps `dplyr::coalesce(c(1,NA), c(2,3))` to see its effect. – ekoam Jan 10 '22 at 01:01

1 Answers1

0

How about using dplyr's case_when?

Test <- structure(list(id=c("1","1","2","1"), date = structure(c(18808, 18808, 18809, 18810
), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
coef = c(4, 1, 6, 1),PV = c(1, "", NA, "")), row.names = c(NA, 4L), class = "data.frame")

library(tidyverse)
Test <- Test %>% 
  mutate(
    PV = case_when(
      is.na(PV) ~ as.character(coef),
      PV == "" ~ as.character(coef),
      TRUE ~ PV
    ),
    PV = as.numeric(PV)
  )
tauft
  • 546
  • 4
  • 13