user236152
user236152

Reputation: 258

R: loop with dplyr

I have multiple objects with names depth_* I want to summarize them like that:

depth_PATH2 %>%
+   summarise(avg = mean(V3), sd = sd(V3), med = median(V3))

which gives:

  avg sd med
1   1  0   1

But I'd link to run a loop over all those files so that I would get a giant table like:

             avg sd med
depth_PATH2   1   0  1
depth_PGTH7   2   7  3
etc.

Can you help? Thanks!

M

Upvotes: 0

Views: 31

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24770

One approach is to use mget from base R to make a list of your data.frames.

Then you can then bind_rows to make them into one data.frame, group_by the object, and summarize.

library(dplyr)
mget(ls(pattern="depth_")) %>%
  bind_rows(.id = "obj") %>%
  group_by(obj) %>%
  summarise(avg = mean(V3), sd = sd(V3), med = median(V3))
## A tibble: 3 x 4
#  obj       avg    sd   med
#  <chr>   <dbl> <dbl> <dbl>
#1 depth_a   2    0      2  
#2 depth_b   4.5  2.12   4.5
#3 depth_c   6    4.24   6  

Sample Data

depth_a <- data.frame(A = c(1,2), V3 = c(2,2))
depth_b <- data.frame(A = c(1,2), V3 = c(6,3))
depth_c <- data.frame(A = c(1,2), V3 = c(9,3))

Upvotes: 1

Related Questions