I have this dataset below:
library(data.table)
set.seed(123)
dt <- data.table(x_1 = c(3,2,2,1,3,2,1,2,3,3),
x_2 = c(2,1,1,3,2,3,3,1,2,3),
x_3 = c(2,3,3,2,1,2,3,3,1,1),
y_1 = sample(2, 10, replace = T),
y_2 = sample(2, 10, replace = T),
y_3 = sample(2, 10, replace = T))
I would like to perform an if else operation on the x columns and if any of the x columns is equal to 1, it would create a new column with the value of the corresponding y column. For e.g. in the 5th row, x_3 = 1, so the new column should return the value corresponding to y_3.
My idea was to return the name of the x column which matches the condition as an intermediate column and then use the value suffix (1,2,3) to extract the value from the corresponding y column.
But the 1st step to create the intermediate column is creating a list and the rows not matching the condition is returning character(0).
cols <- c("x_1", "x_2", "x_3")
dt$int <- apply(dt[,..cols], 1, function(x) names(which(x == 1)))
My desired output:
x_1 x_2 x_3 y_1 y_2 y_3 new
3 2 2 1 2 2 NA
2 1 3 2 1 2 1
2 1 3 1 2 2 2
1 3 2 2 2 2 2
3 2 1 2 1 2 2
2 3 2 1 2 2 NA
1 3 3 2 1 2 2
2 1 3 2 1 2 1
3 2 1 2 1 1 1
3 3 1 1 2 1 1
Any ideas on how to achieve this? A data-table based solution would be preferable.