Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

issue in dplyr: unwanted NA's in new column

I have the following data frame:

Xnumber   Number
X17339    EWY
X17339    LW2Y
X17401    EWC
X17401    LWY
X17466    EWC
X17466    LWY 
X17466    EWY
X17466    LWC

I want to create a new column, Number2, using the following code:

library(dplyr 
df3<-df3 %>% group_by(Xnumber) %>% mutate(Number2=if_else(lead(Number)=="LWC","Unknown",Number))

This is what I the resulting data frame should look like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    Xnumber   Number   Number2
    X17339    EWY      EWY
    X17339    LW2Y     LW2Y
    X17401    EWC      EWC
    X17401    LWY      LWY
    X17466    EWC      EWC
    X17466    LWY      LWY
    X17466    EWY      Unknown
    X17466    LWC      LWC

But instead, I also get NA’s in my new column, like this.

    Xnumber   Number   Number2
    X17339    EWY      EWY
    X17339    LW2Y     NA
    X17401    EWC      EWC
    X17401    LWY      NA
    X17466    EWC      EWC
    X17466    LWY      LWY
    X17466    EWY      Unknown
    X17466    LWC      NA

I’m not sure why this is happening. Any thoughts?

>Solution :

Use default:

library(dplyr)
 
df3<-df3 %>% 
  group_by(Xnumber) %>% 
  mutate(Number2=if_else(lead(Number, default = "") == "LWC","Unknown",Number))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading