0

I generally use first approach to aggregate multiple columns in a data frame. But I noticed the result was wrong. So I split it into multiple steps as shown in approach 2, and the results are correct

Why this is happening? why the results in approach 1 are different from approach 2

`

# Approach 1
  inv=aggregate(cbind(total,type1,type2,type3,type4)~pn,data=inventory,FUN=sum,na.rm=T)
  
# Approach 2
  invv=aggregate(total~pn,data=inventory,FUN=sum,na.rm=T)
  invv=merge(invv,aggregate(type1~pn,data=inventory,FUN=sum,na.rm=T),by='pn',all=T)
  invv=merge(invv,aggregate(type2~pn,data=inventory,FUN=sum,na.rm=T),by='pn',all=T)
  invv=merge(invv,aggregate(type3~pn,data=inventory,FUN=sum,na.rm=T),by='pn',all=T)
  invv=merge(invv,aggregate(type4~pn,data=inventory,FUN=sum,na.rm=T),by='pn',all=T)

`

Tried to aggregate different types of inventories from a data frame by part number, but the result (approach 1) was wrong. However, when it was done in multiple steps (approach 2), the result was correct.

Hoseinbf
  • 13
  • 3
  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Nov 30 '22 at 21:43
  • I am new here. How can I upload the csv file? – Hoseinbf Nov 30 '22 at 21:50
  • Include `na.action = identity` – Onyambu Nov 30 '22 at 22:05

1 Answers1

0

Gotcha, although I have na.rm=T in all my summations, existence of NA in data frame causes a problem in the first approach. when replaced NA by "0", the results were okay

Hoseinbf
  • 13
  • 3
  • 2
    I wouldn't recommend doing that as a habit. NA and 0 are not the same, even if they happen to give the same result in this particular case. There are existing ways to make sure NA values are processed properly by `aggregate`, via the `na.action=` argument as Onyambu notes in the comments to the question above. Here's a link to an answer showing how this works - https://stackoverflow.com/a/66686413/496803 – thelatemail Nov 30 '22 at 22:12