0

This can be a repetition but I didn't really find any specific post on the same.

I have two dataframes "df" and "nm". They have same rows and columns and also column names are same.

df
User    Apple   Cherry  Kiwi    Lemon
A       208      71     129     58
B       81       69     142     53
C       164      212    175     200
D       125      73     51      214
E       205      123    46      75
F       53      215     40      38

nm
User    Lemon   Cherry  Apple   Kiwi
A        161     57      27      38
B        26      153     57      45
C        39      153     219     86
D        47      155     139     61
E       143      40      59     130
F       183      77      71     133

Note that column index for similar column names are not same.

I want to create new data frame "kl" where I want the aggregate value as per "User" for each column name i.e.

kl
User    Apple   Cherry  Kiwi    Lemon
A       117.5    64     83.5    109.5
B       69       111    93.5    39.5
C       191.5    182.5  130.5   119.5
D       132      114    56      130.5
E       132      81.5   88      109
F        62      146    86.5    110.5
Tensibai
  • 15,557
  • 1
  • 37
  • 57
ROY
  • 268
  • 2
  • 11
  • 2
    Can you provide the output of `dput` on those data frames so we can create them really easily? Otherwise we have to faff about making them from your text. Also your "aggregate" is the mean, yes? – Spacedman Jan 25 '17 at 10:49
  • I am fully agreed with @Tensibai – ROY Jan 25 '17 at 11:29

1 Answers1

3

You can try to aggregate, the 2 rbind-ed data.frames, doing first a reordering of the columns so they are in the same order in both data.frames:

aggregate(.~User, data=rbind(df, nm[, match(colnames(df), colnames(nm))]), FUN=mean)
#  User Apple Cherry  Kiwi Lemon
#1    A 117.5   64.0  83.5 109.5
#2    B  69.0  111.0  93.5  39.5
#3    C 191.5  182.5 130.5 119.5
#4    D 132.0  114.0  56.0 130.5
#5    E 132.0   81.5  88.0 109.0
#6    F  62.0  146.0  86.5 110.5
Cath
  • 23,906
  • 5
  • 52
  • 86