0

is there an easy/straightforward way to merge dataframes from a list that have a common column? I tried sapply but didn't quite know how to index properly.

So for example, my list looks like this:

rms.byhr

$band1
   Group.1        x
1        0 105.0167
2        1 104.8673
3        2 104.7015
4        3 104.6000
5        4 104.9439
6        5 105.0677
7        6 104.6434
8        7 104.2099
9        8 103.7765
10       9 103.3561

$band2
   Group.1        x
1        0 94.48735
2        1 94.25948
3        2 94.18401
4        3 94.09341
5        4 94.33667
6        5 94.85422
7        6 94.59766
8        7 94.32328
9        8 93.93813
10       9 93.78168

I tried

rms.byhr<-as.data.frame(sapply(rms.byhr, function(x){merge(rms.byhr$x, by=rms.byhr$Group.1)})

But I can see why this doesn't work. Is there a way to index the prior or next element in a list using sapply?

I could just write a loop, but this seems more complicated. Also, I'd like it to be able to "work" even if I only have one DF in my list (or would give merge an error no matter what and I would need to make a conditional?)

Anke
  • 527
  • 1
  • 6
  • 19
  • you need `merge`, check for `?merge`, use it with `Reduce` – Agaz Wani Apr 06 '18 at 16:31
  • @AaghazHussain The OP is already using `merge()` in their `sapply()`. I don't think that's the problem. – MrFlick Apr 06 '18 at 16:32
  • `Reduce(function(x, y) merge(x, y, by = c("Columan name"), all=TRUE), data)` – Agaz Wani Apr 06 '18 at 16:34
  • If you use `Group.1`, then u should replace `column name`, with `Group.1 ` and `data` is your `list`. Look at the links provided. If it does not solve your problem, Edit your question and tell us how your question is different and what errors you get. – Agaz Wani Apr 07 '18 at 05:27
  • I apologize for the duplicate - when I wrote my question, for some reason it didn't pop up as a suggestion. I will have a look at those answer. @Aaghaz, thank you, that worked great! Is there away to avoid the warning of duplicate names, i.e. keep the names from the list for example? – Anke Apr 07 '18 at 05:38
  • Is it not keeping the `row names` for you ??, remove the duplicates if you want. – Agaz Wani Apr 07 '18 at 06:19

0 Answers0