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

R combine two columns with opposite values and NA values, into one column, and delete existing

I have a dataframe that looks like this:

structure(list(RFM_Score_Meaning.x = c("Dropped", "Dropped", 
"Dropped", "Dropped", "Dropped", "Dropped", "Dropped", NA, NA, 
NA, NA, NA, NA, NA, NA, NA), RFM_Score_Meaning.y = c(NA, NA, 
NA, NA, NA, NA, NA, "Need Encouragement", "Need Encouragement", 
"Need Encouragement", "Need Encouragement", "Need Encouragement", 
"Need Encouragement", "Need Encouragement", "Need Encouragement", 
"Need Encouragement")), row.names = c(NA, -16L), class = c("tidytable", 
"data.table", "data.frame"), .internal.selfref = <pointer: 0x000002470fabbfe0>)


RFM_Score_Meaning.x
<chr>
RFM_Score_Meaning.y
<chr>
Dropped NA          
Dropped NA          
Dropped NA          
Dropped NA          
Dropped NA          
Dropped NA          
Dropped NA          
NA  Need Encouragement          
NA  Need Encouragement          
NA  Need Encouragement

This dataframe is two columns. The places that are NA in the first column have values in the second column, and vice-versa.

How do I get rid of these two columns and instead have one column that that has all the values without any NA values?

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

>Solution :

We could use coalesce:

library(dplyr)
df %>% 
  transmute(RFM_Score_Meaning = coalesce(RFM_Score_Meaning.x, RFM_Score_Meaning.y))
     RFM_Score_Meaning
 1:            Dropped
 2:            Dropped
 3:            Dropped
 4:            Dropped
 5:            Dropped
 6:            Dropped
 7:            Dropped
 8: Need Encouragement
 9: Need Encouragement
10: Need Encouragement
11: Need Encouragement
12: Need Encouragement
13: Need Encouragement
14: Need Encouragement
15: Need Encouragement
16: Need Encouragement
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