Reputation: 3752
I have a list
test_list = list(foo = c( "a","b","c"), bar = c("First", "Second"))
test_list
# $foo
# [1] "a" "b" "c"
# $bar
# [1] "First" "Second"
I want to assign names to each element of vector, which I get from levels of data frame
annotation = data.frame(foo = factor(c(rep(1,3),rep(2,2), rep(3,1))),
bar = factor(c(rep('Male',2), rep('Female',4)) ))
# foo bar
# 1 Male
# 1 Male
# 1 Female
# 2 Female
# 2 Female
# 3 Female
I can extract the levels as follows:
lapply(annotation, levels)
I can assign names one-by-one:
names(test_list$foo) <- levels(annotations$foo)
However, as I have much longer list in reality, I'd like to vectorize naming procedure. Number of columns in data frame matches exactly number of elements in the list; number of levels of each factor matches exactly number of elements in vectors, which are elements of the list.
How can I do that without going into loop?
Upvotes: 1
Views: 123
Reputation: 887158
We can use Map
to assign names to list
elements of test_list
by the levels
of corresponding columns of annotation
.
test_list <- Map(setNames, test_list, lapply(annotation, levels))
Upvotes: 1