AnswerBun.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!

Related Questions

What will this recursive function yield?

1  Asked on December 9, 2021 by user13812739

     

How to style Rebass Switch

5  Asked on December 9, 2021 by amaster

       

Redis Cluster Mode – replicas not working

1  Asked on December 9, 2021 by ramprakash

     

Disable seeking in mediaelement.js

1  Asked on December 9, 2021 by pelirrojo

         

Table not getting created sqlite android

4  Asked on December 9, 2021 by user3844417

   

Angularjs using JWT breaks CORS to Amazon S3 on login

2  Asked on December 9, 2021 by codephobia

     

Write a value with opc ua Python

2  Asked on December 9, 2021

   

unable to install vue chart.js in vue

2  Asked on December 9, 2021 by prabina-sht

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir