Combine column to remove NA's yet prioritize specific replacements

限于喜欢 提交于 2019-12-04 15:10:38

Use max.col and some matrix indexing (specifying which row/col combination to take):

cbind(1:nrow(data), max.col(!is.na(data[-1]), "last"))
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    2
#[3,]    3    3
#[4,]    4    1
#[5,]    5    3
#[6,]    6    3

data[-1][cbind(1:nrow(data), max.col(!is.na(data[-1]), "last"))]
#[1] 99  2  4  3  4  5

cbind(data[1], result=data[-1][cbind(1:nrow(data), max.col(!is.na(data[-1]), "last"))])
#  a result
#1 A     99
#2 B      2
#3 C      4
#4 D      3
#5 E      4
#6 F      5

If you need a particular column to always be given precedence, make a temporary object with the columns in a particular order, and then process it:

tmp <- data[-1][c("z", setdiff(names(data[-1]), "z"))]
tmp[cbind(1:nrow(tmp), max.col(!is.na(tmp), "first"))]
#[1] 99  2  4  3  4  5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!