achai
achai

Reputation: 309

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

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.

Upvotes: 2

Views: 1236

Answers (3)

akrun
akrun

Reputation: 887128

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" 

Upvotes: 0

Darren Tsai
Darren Tsai

Reputation: 35554

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"

Upvotes: 3

Allan Cameron
Allan Cameron

Reputation: 173813

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" 

Upvotes: 2

Related Questions