Home > front end >  Insert the same value from one column to another in R
Insert the same value from one column to another in R

Time:01-10

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 

CodePudding user response:

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)
  )
  •  Tags:  
  • Related