How to implement coalesce efficiently in R

前端 未结 8 2451
深忆病人
深忆病人 2020-11-21 23:20

Background

Several SQL languages (I mostly use postgreSQL) have a function called coalesce which returns the first non null column element for each row. This can b

8条回答
  •  盖世英雄少女心
    2020-11-22 00:13

    Here is my solution:

    coalesce <- function(x){ y <- head( x[is.na(x) == F] , 1) return(y) } It returns first vaule which is not NA and it works on data.table, for example if you want to use coalesce on few columns and these column names are in vector of strings:

    column_names <- c("col1", "col2", "col3")

    how to use:

    ranking[, coalesce_column := coalesce( mget(column_names) ), by = 1:nrow(ranking)]

提交回复
热议问题