TransWikia.com

How to swap my list element's name and value in R?

Stack Overflow Asked by achai on December 19, 2020

I have a list:

l <- list(1:3, 4:6)
names(l[[1]]) <- c("A1","B1","C1")
names(l[[2]]) <- c("A2","B2","C2")
l

[[1]]  
A1 B1 C1   
 1  2  3 

[[2]]  
A2 B2 C2   
 4  5  6  

I would like to switch my list element’s value and name, so the output like this:

[[1]]  
1 2 3  
A1 B2 C3  

[[2]]  
4 5 6  
A2 B2 C2  

In my real list, I have 200 + sublist and each sublist have 100+ element. Is there any efficient way can achieve this in R?

Thank you in advance.

3 Answers

You can do:

lapply(l, function(x) `names<-`(names(x), x))
#> [[1]]
#>    1    2    3 
#> "A1" "B1" "C1" 
#> 
#> [[2]]
#>    4    5    6 
#> "A2" "B2" "C2" 

Correct answer by Allan Cameron on December 19, 2020

We can use enframe/deframe with map

library(tibble)
library(purrr)
library(dplyr)
map(l, ~ enframe(.x) %>%
            select(2:1) %>% 
            deframe)
#[[1]]
#   1    2    3 
#"A1" "B1" "C1" 

#[[2]]
#   4    5    6 
#"A2" "B2" "C2" 

Answered by akrun on December 19, 2020

A base solution with lapply() and setNames().

lapply(l, function(x) setNames(names(x), x))

Or you can use enframe() with deframe() from tibble.

library(tibble)
lapply(l, function(x) deframe(enframe(x)[2:1]))

Both of them give

# [[1]]
#    1    2    3 
# "A1" "B1" "C1" 
# 
# [[2]]
#    4    5    6 
# "A2" "B2" "C2"

Answered by Darren Tsai on December 19, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP