Try to search your question here, if you can't find : Ask Any Question Now ?

Creating new column with dplyr::if_else condition in R

HomeCategory: stackoverflowCreating new column with dplyr::if_else condition in R
bhawya asked 2 weeks ago

I have written the following code to create a new column based on certain conditions on the previous column. I believe I need to add an additional condition to retain the previous values.

BP2018_spread <- BP2018_spread  %>%
 dplyr :: mutate(Period_Type = if_else(grepl("QTD",BP2018_spread$Month), 'QTD', if_else(grepl("YTD",BP2018_spread$Month),'YTD', 'NA')))

Current Output:
       Month      Period_Type
       <chr>      <chr>      
     1 " Apr"     NA         
     2 " Apr QTD" QTD        
     3 " Apr YTD" YTD        
     4 " Aug"     NA         
     5 " Aug QTD" QTD        
     6 " Aug YTD" YTD        
     7 " Dec"     NA         
     8 " Dec QTD" QTD        
     9 " Dec YTD" YTD        
    10 " Feb"     NA  


Desired Output:
   Month      Period_Type
       <chr>      <chr>      
     1 " Apr"     Apr         
     2 " Apr QTD" QTD        
     3 " Apr YTD" YTD        
     4 " Aug"     Aug         
     5 " Aug QTD" QTD        
     6 " Aug YTD" YTD        
     7 " Dec"     Dec         
     8 " Dec QTD" QTD        
     9 " Dec YTD" YTD        
    10 " Feb"     Feb   

OR

Desired Output:
       Month      Period_Type
           <chr>      <chr>      
         1 " Apr"     MTD         
         2 " Apr QTD" QTD        
         3 " Apr YTD" YTD        
         4 " Aug"     MTD         
         5 " Aug QTD" QTD        
         6 " Aug YTD" YTD        
         7 " Dec"     MTD         
         8 " Dec QTD" QTD        
         9 " Dec YTD" YTD        
        10 " Feb"     MTD   
1 Answers
Best Answer
Arben answered 2 weeks ago
Your Answer

9 + 5 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com