Insert the same value from one column to another in R

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

Expected output

 > Test
      id       date Category coef   PV
    1  1 2021-06-30      FDE    4    1
    2  1 2021-06-30      ABC    1    1
    3  2 2021-07-01      FDE    6    6
    4  1 2021-07-02      ABC    1    1

You could use dplyr::case_when

Note, it is done this way (with the as.character) because you have set the initial PV column as a string in your example. Otherwise, you could remove the as.character bits.

library(tidyverse)
Test %>% 
  mutate(PV = case_when(PV == "" ~ as.character(coef),
                        is.na(PV) ~ as.character(coef),
                        TRUE ~ as.character(PV)))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.