Jack Arnestad
Jack Arnestad

Reputation: 1865

Conversion of dataframe into specially formatted list for use in function

I have a data frame like the following:

df = data.frame(name = c("chr", "test"), ncol = c(2, 3))

However, for input into a function (ComplexHeatmap), I need a list like the following:

list(chr = list(ncol = 2), test = list(ncol = 3))

What is the easiest way to convert from this data frame into a list of this format? Doing as.list does not get the right format.

Thanks! Jack

Upvotes: 2

Views: 26

Answers (2)

akrun
akrun

Reputation: 887118

One option would be split from base R

split(setNames(as.list(df$ncol), rep('ncol', nrow(df))), df$name)

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48211

One approach would involve using plyr. I suspect you may also have more than those two columns, so let

df <- data.frame(name = c("chr", "test"), ncol = c(2, 3), a = 1:2)
#   name ncol a
# 1  chr    2 1
# 2 test    3 2

Then

dlply(df, .(name), function(r) as.list(r[-1]))
# $chr
# $chr$ncol
# [1] 2
#
# $chr$a
# [1] 1
#
#
# $test
# $test$ncol
# [1] 3
#
# $test$a
# [1] 2
#
#
# attr(,"split_type")
# [1] "data.frame"
# attr(,"split_labels")
#   name
# 1  chr
# 2 test

Upvotes: 2

Related Questions