简体   繁体   中英

How to unite 2 columns with all non-unique or NA values, without dropping cases (keep NA, merge duplicates) in R

I created a dataframe in R. Here is a sample 4-row excerpt (actual df is 13000 rows):

   colA  colB
1  89    89
2  NA    NA
3  90    NA
4  NA    91

Where NA are empty values. Each case contains either duplicate values for each variable, 2 empty values, or 1 empty value.

I want to unite the columns into 1 column, or create new column, where:

  • Each case is preserved in the output
  • If values are duplicates, value in the output is that same value (NOT applying any arithmetic - I do not want to add/multiply the values; and NOT simply pasting the values next to each other)
  • If each value is NA(empty), output value is NA(empty)
  • If a value is NA(empty) and the other is an actual value, output should be the actual value

This is the output I want:

   colC  
1  89    
2  NA    
3  90    
4  91    

I will need to perform this on 2 columns of my 13000 row df.

Wew can use coalesce

library(dplyr)
df1 %>%
   transmute(ColC = coalesce(ColA, ColB))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM