paljenczy
paljenczy

Reputation: 4899

R - two data frame columns to list of key-value pairs

Say I have a data frame

DF1 <- data.frame("a" = c("a", "b", "c"), "b" = 1:3)

What is the easiest way to turn this into a list?

DF2 <- list("a" = 1, "b" = 2, "c" = 3)

It must be really simple but I can't find out the answer.

Upvotes: 6

Views: 4634

Answers (2)

abalter
abalter

Reputation: 10393

The tidy 2023 way would be to use deframe:

tibble(
  key = c("key1", "key2", "key3"),
  value = c("val1", "val2", "val3")
) %>%
deframe()

#   key1   key2   key3 
# "val1" "val2" "val3" 

tibble(
  key = c("key1", "key2", "key3"),
  value = c("val1", "val2", "val3")
) %>%
deframe() %>%
as.list()

# $key1
# [1] "val1"
#
# $key2
# [1] "val2"
#
# $key3
# [1] "val3"

Upvotes: 0

MrFlick
MrFlick

Reputation: 206486

You can use setNames and as.list

DF2 <- setNames(as.list(DF1$b), DF1$a)

Upvotes: 11

Related Questions