通过优先排列其中一列来合并数据框中的两列 [英] Merge 2 columns in dataframe by prioritize one of them

查看:93
本文介绍了通过优先排列其中一列来合并数据框中的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下data.frame:

Assuming that I have the following data.frame:

Value1    Value2
   'a'      <NA>
  <NA>       'b'
  <NA>       'c'
   'd'       'e'
   'f'       'g'
  <NA>      <NA>

我如何通过说第一列具有优先级"来将这些列组合在一起,这意味着如果两个列都具有从第一列开始的chouse值.所以结果应该是:

How can I compine these columns in one by saying that the first column has the 'priority', meaning that if both columns have value chouse from the first one. SO the result should be:

Value3
    'a'
    'b'
    'c'
    'd'
    'f'
   <NA>

其中<NA>不是可用值.

推荐答案

这是使用max.col的简单方法(我假设它们是真实的NA s)

Here's a simple method using max.col (I'm assuming these are real NAs)

df[cbind(1:nrow(df), max.col(!is.na(df), ties.method = "first"))]
# [1] "a" "b" "c" "d" "f" NA 

如果这些不是真实的NA,则可以

If these aren't real NAs, you could do

df[cbind(1:nrow(df), max.col(df != "<NA>", ties.method = "first"))]

或者使用is.na(df) <- df == "<NA>"将它们转换为NA,然后尝试第一个解决方案.

Or alternatively convert them to NAs using is.na(df) <- df == "<NA>" and then try the first solution.

这篇关于通过优先排列其中一列来合并数据框中的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆