Getting the position of the the last non-NA value in a row in an R data.table

Viewed 91

Suppose I have the following data.table, with four students and their answers to four questions:

library(data.table)
dt <- data.table(
  student = 1:4,
  q1 = c(1, 1, 1, NA),
  q2 = c(2, 2, NA, NA),
  q3 = c(3, NA, 3, NA),
  q4 = c(4, NA, NA, NA)
)
# dt
#    student q1 q2 q3 q4
# 1:       1  1  2  3  4
# 2:       2  1  2 NA NA
# 3:       3  1 NA  3 NA
# 4:       4 NA NA NA NA

What is an elegant r data.table way to get the first non-NA value from the right in each row (but within the question columns q1 through q4) to get the last_q_answered column below?

#    student q1 q2 q3 q4 last_q_answered
# 1:       1  1  2  3  4               4
# 2:       2  1  2 NA NA               2
# 3:       3  1 NA  3 NA               3
# 4:       4 NA NA NA NA               0
2 Answers

We can use max.col :

max.col(!is.na(dt[, -1]), ties.method = 'last') * +(rowSums(!is.na(dt[,-1])) > 0)
#[1] 4 2 3 0

We can use melt with join on the 'student'

library(data.table)
dt[melt(dt, id.var = 'student', na.rm = TRUE)[, 
     value[.N], .(student)], last_q_answered := V1, on = .(student)][]
Related