Imagine I have the following list
> test <- list("a" = 1, "b" = 2)
Each list item has a name:
> names(test)
Now I want to extract this name using lapply() , because I want to use it in a new function that will be called using lapply. I just don't know how to extract the name of each element.
I tried using deparse() and substitute() , but the result was strange:
> lapply(test, function(x) {deparse(substitute(x))}) $a [1] "X[[i]]" $b [1] "X[[i]]"
Somebody knows?
Accuracy:
I want to do something like this: I have a list that looks like a test:
> test <- list("a" = matrix(1, ncol = 3), "b" = matrix(2, ncol = 3))
I want to apply a function to this list that converts data inside each element and gives a specific name for each column:
make_df <- function(x) { output <- data.frame(x) names(output) <- c("items", "type", NAME_OF_X) return(output) } lapply(test, make_df)
Expected Result:
> test $a [,1] [,2] [,3] [1,] 1 1 1 attr(,"names") [1] "index" "type" "a" $b [,1] [,2] [,3] [1,] 2 2 2 attr(,"names") [1] "index" "type" "b"
I do not know how I can get the name of an element to indicate a name for my third column.