I have a following dataset with 100 variables Z1 to Z100 containing character values and 10 variables containing column numbers.
Z1 | ... | Z100 | V1 | ... | V10 |
---|---|---|---|---|---|
NA | ... | xyz | 56 | ... | NA |
An exemplary dataset - with 5 rows, 5 Z-variables (Z1-Z5) and 3 V-variables (V1-3) and 3 created variables V1_1-V1_3:
structure(list(Z1 = c("aaa", NA, "aaa", NA, "aaa", NA, "aaa"),
Z2 = c("bbb", "bbb", "bbb", "bbb", "bbb", NA, "bbb"), Z3 = c("ccc",
"ccc", NA, "ccc", "ccc", "ccc", "ccc"), Z4 = c("ddd", "ddd",
NA, "ddd", NA, "ddd", "ddd"), Z5 = c("eee", "eee", "eee",
"eee", "eee", "eee", NA), V1 = c(1, 3, 4, NA, 2, 2, NA),
V2 = c(NA, 3, 3, NA, 5, NA, 1), V3 = c(4, 4, 4, NA, 5, 5,
NA), V1_1 = c("aaa", "ccc", NA, NA, "bbb", NA, NA), V2_1 = c(NA,
"ccc", NA, NA, "eee", NA, "aaa"), V3_1 = c("ddd", "ddd",
NA, NA, "eee", "eee", NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -7L))
I'd like to create a set of 3 new variables V1_1 to V3_1, where each will contain a character value from a column which number was in original V variable.
Technically one could do the following:
dataset %>% mutate(., V1_1 = c_across(1:5)[V1],
...
V3_1 = c_across(1:5)[V3]
)
Just not to do it step by step, I've tried the following with across:
dataset %>%
mutate(across(V1:V3, dataset[,.], .names = "{col}_1"))
But I got an error:
Error in `mutate()`:
! Problem while computing `..1 = across(V1:V3, m3[, .], .names = "{col}_1")`.
Caused by error in `.subset()`:
! invalid subscript type 'list'