简体   繁体   English

如何在 R 中将 2 列与所有非唯一值或 NA 值合并,而不丢弃案例(保留 NA,合并重复项)

[英]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.我在 R 中创建了一个 dataframe。 Here is a sample 4-row excerpt (actual df is 13000 rows):这是一个示例 4 行摘录(实际 df 为 13000 行):

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

Where NA are empty values.其中 NA 是空值。 Each case contains either duplicate values for each variable, 2 empty values, or 1 empty value.每个案例包含每个变量的重复值、2 个空值或 1 个空值。

I want to unite the columns into 1 column, or create new column, where:我想将列合并为 1 列,或创建新列,其中:

  • Each case is preserved in the output每个案例都保存在 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)如果值重复,则 output 中的值是相同的值(不应用任何算术 - 我不想添加/乘以这些值;而不是简单地将值粘贴在一起)
  • If each value is NA(empty), output value is NA(empty)如果每个值为 NA(empty),则 output 值为 NA(empty)
  • If a value is NA(empty) and the other is an actual value, output should be the actual value如果一个值为 NA(empty) 而另一个为实际值,则 output 应为实际值

This is the output I want:这是我想要的 output:

   colC  
1  89    
2  NA    
3  90    
4  91    

I will need to perform this on 2 columns of my 13000 row df.我需要在我的 13000 行 df 的 2 列上执行此操作。

Wew can use coalesce我们可以使用coalesce

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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