I have a data.table similar to the following:
foo bar a1 a2 a3 b1 b2 b3 b4 c1 c2 A_1 A_2 A_3 C_1 C_2
m 19 0 1 2 2 1 3 0 0 2 25 33 61 50 50
f 30 1 2 1 0 4 2 1 2 2 10 43 30 45 73
n 22 0 2 2 1 3 1 0 1 2 7 84 33 12 40
I would like to transform this to a long format, with a row for each lowercase letter variable. At the same time, I would like to carry along also uppercase variables that match the lowercase ones, and introduce NAs when there is no match. Here is a snippet of the end result:
foo bar lower lower_value upper upper_value
m 19 a1 0 A_1 25
m 19 a2 1 A_2 33
...
f 30 b4 1 B_4 NA
...
n 22 c2 2 C_2 40
What is the best way to achieve this?
EDIT: here the data.table for reference:
library(data.table)
dt <- data.table(
foo = c("m", "f", "n"),
bar = c(19, 30, 22),
a1 = c(0, 1, 0),
a2 = c(1, 2, 2),
a3 = c(2, 1, 2),
b1 = c(2, 0, 1),
b2 = c(1, 4, 3),
b3 = c(3, 2, 1),
b4 = c(0, 1, 0),
c1 = c(0, 2, 1),
c2 = c(2, 2, 2),
A_1 = c(25,10,7),
A_2 = c(33,43,84),
A_3 = c(61,30,33),
C_1 = c(50,45,12),
C_2 = c(50,73,40)
)