kamiks
kamiks

Reputation: 184

Transform List of Lists into a Summary Table

Relative newbie to R here. I am having difficulty transforming a list of lists into a cleaner summary table. Generally speaking, I am looking to apply numerous functions to a dataframe with multiple columns and obtain a summary table as an output where the rownames are the names of the functions and the column names are the same as the column names of the dataframe.

Take the following sample code. Say I create the following simple dataframe:

a = seq(100,110,2)
b = seq(200,220,4)
df = data.frame(a,b)

Next, say I create the following two sample functions, each of which will take a numerical vector and result in a single numerical number:

func1 = function(x) sum(x)**2
func2 = function(x) sqrt(sum(x))

I then wanted to wrap these two functions into a single function which will run them both:

combined_func = function(x){
  combined = list("func1" = func1(x), "func2" = func2(x))
  return(as.data.frame(do.call(rbind, combined)))
}

I then applied this "combined function" to both columns of my dataframe, like this:

lapply(df, combined_func)

And here was the output I obtained:

$a
               V1
func1 396900.0000
func2     25.0998

$b
                V1
func1 1.587600e+06
func2 3.549648e+01

While the output is technically correct, I hate the formatting. As stated at the top, I'd like the end result to be the names of the functions as the rownames, and the names of the columns ("a" and "b" in this example) to be the column names. I'd like the result to look like this:

                  a            b
func1   396900.0000 1.587600e+06
func2       25.0998 3.549648e+01

I've spent the last few days searching StackOverflow and can't seem to figure out how to accomplish this. Any and all help would be very much appreciated!

Upvotes: 1

Views: 309

Answers (4)

Ronak Shah
Ronak Shah

Reputation: 388817

You can change combined_func to :

combined_func = function(x){
  c("func1" = func1(x), "func2" = func2(x))
}

and call it with sapply :

sapply(df, combined_func)
#             a         b
#func1 396900.0 1587600.0
#func2     25.1      35.5

Upvotes: 0

nniloc
nniloc

Reputation: 4243

A slightly different approach, which saves the need for the the combined_func

funs <- list(func1 = func1, func2 = func2)

t(sapply(funs, mapply, df))

#-----
                a            b
func1 396900.0000 1.587600e+06
func2     25.0998 3.549648e+01

Upvotes: 1

AdamO
AdamO

Reputation: 4910

Could it be as easy as

Reduce(cbind, lapply(df, combined_func))

?

Upvotes: 0

Matt
Matt

Reputation: 7385

You can do:

combined <- lapply(df, combined_func)

table <- do.call(cbind, combined)

colnames(table) <- list('a', 'b')

This gives us:

               a            b
func1 396900.0000 1.587600e+06
func2     25.0998 3.549648e+01

Upvotes: 1

Related Questions