I have an appearingly very simple task but can't figure out what I'm doing wrong. I have a list of 3 Xx2 tibbles (in the example 2x2) having a character vector and an integer vector. I want to convert it to a list of 3 named vectors where the letters are the vector elements and the numbers are the names. Here is my approach:
tbl <- tibble(numbers=c(1:2), letters=letters[1:2])
vec_names <- c("name1", "name2", "name3")
lst <- list(tbl, tbl, tbl)
names(lst) <- vec_names
lst_n <- lapply(lst, function(x) x[["letters"]])
lst_n <- sapply(vec_names,
function(x) names(lst_n[[x]]) <- lst[[x]]$numbers)
I get this result
lst_n
name1 name2 name3
[1,] 1 1 1
[2,] 2 2 2
and I can't see my mistake. Doing
names(lst_n[["name1"]]) <- lst[["name1"]]$numbers
gives me exactly what I want for "name1" but why doesn't it work with sapply?
I had [] before and changed it to [[]] to access the tibbles inside the list instead of the list elements but it still doesn't work. Can anyone help? It seems like a very basic task.