Подход, использующий data.table
#library( data.table )
DT <- data.table( col1 = c(1,NA, 1, NA, 1),
col2 = c(NA, 1, NA, 1, NA) )
# col1 col2
# 1: 1 NA
# 2: NA 1
# 3: 1 NA
# 4: NA 1
# 5: 1 NA
#update non-NA values to colnumbers
DT[, c("col1", "col2") := as.data.table( ifelse( is.na(DT), NA, col(DT) ) )]
#final output
DT[, .(col1 = fcoalesce( col1, col2 ) ) ][]
# col1
# 1: 1
# 2: 2
# 3: 1
# 4: 2
# 5: 1
обновление с предоставленными образцами данных
d2 <- data.frame(col1 = c('', 1, '', 1, '', 1),
col2 = c('', '', 1, '', 1, ''),
col3 = c(1, '', '', '', '', ''), stringsAsFactors = FALSE)
setDT(d2)
cols <- names(d2)
#update values to colunumbers
d2[, (cols) := as.data.table( ifelse( d2 == '', NA, col(d2) ) )]
#final output
d2[, .(col1 = fcoalesce( d2 ) ) ][]
# col1
# 1: 3
# 2: 1
# 3: 2
# 4: 1
# 5: 2
# 6: 1