Neil
Neil

Reputation: 8247

comparing two data frames columns

I have two dataframes in r

df1

NO     QC1     QC2      QC3     Total 
123      8       8        8     24 
124      9       8        8     25
125      9       9        9     27

df2

NO     QC1     QC2      QC3     Total 
123      7       7        7      21 
124      9       10       8      27
125      10      10       10     30

I want to compare above dataframes with total. whichever row has maximum total will be kept. My desired dataframe is as follows

NO     QC1     QC2      QC3    Total 
123     8       8        8      24 
124     9       10       8      27
125     10      10       10     30

NO column is unique in both the dataframes. How can I do it in R?

Upvotes: 0

Views: 73

Answers (1)

akrun
akrun

Reputation: 887831

We can use pmax to get the elementwise max between two datasets having the same dimension

pmax(df1, df2)
#   NO QC1 QC2 QC3 Total
#1 123   8   8   8    24
#2 124   9  10   8    27
#3 125  10  10  10    30

If there are multiple datasets, place it in a list and then use pmax with do.call

do.call(pmax, list(df1, df2))

If we are comparing only the 'Total' column, perhaps

t(sapply(seq_len(nrow(df1)), function(i) 
      if(df1$Total[i] > df2$Total[i]) df1[i,] else df2[i,]))

Upvotes: 5

Related Questions