0

I have a function returning data frame like this:

TERM  Freq

GO1    1
GO2    5
GO3    4

I'm calling the function multiple times using lapply, and I want to average all the results receive (Freq column) by the TERM column. Note that each run may return slightly different terms.

The results of the lapply function looks like:

enter image description here

Thanks!

Rachel Rap
  • 55
  • 5
  • 2
    So what is your question? – user2974951 Jun 29 '21 at 12:56
  • Further, this question would really benefit from being reproducible (and a picture of a summary of data is not helpful). Please read from https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info, and then [edit] your question and add sample data using `dput(x)` where `x` is a representative sample. If your function is not important, then give a sample of the result from that `lapply(., yourfunc)` call so that we can better see what you want to aggregate. Thanks! – r2evans Jun 29 '21 at 13:09

1 Answers1

1

Here is a dplyr solution.

Sample data:

dat1 <- read.table(header = TRUE, text = '
TERM  Freq
GO1    1
GO2    5
GO3    4')


dat2 <- read.table(header = TRUE, text = '
TERM  Freq
GO1    1
GO2    2
GO3    1')



dat3 <- read.table(header = TRUE, text = '
TERM  Freq
GO1    2
GO2    3
GO3    4')


lst <- list(dat1, dat2, dat3)

Solving take two steps. First combine the list into a single data frame. Then perform the grouping and summarization. Like this:

library(dplyr)


grp <- bind_rows(lst) %>% 
  group_by(TERM) %>% 
  summarize(mean = mean(Freq))

grp
# # A tibble: 3 x 2
#   TERM   mean
#   <chr> <dbl>
# 1 GO1    1.33
# 2 GO2    3.33
# 3 GO3    3 


David J. Bosak
  • 1,386
  • 12
  • 22