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