0

I am trying to sum up the column by sj and hid with ave. My code: mutate(h97 = with(df,ave(hhh97,sj,hid,FUN = sum))).
I want to get the following result:

sj  hid  hhh97  h97
-------------------
1995 1   1      1
1995 1   0      1
1995 2   2      3
1995 2   1      3 

However, I got the following result and the warning message:

sj  hid  hhh97  h97
-------------------
1995 1   1      1
1995 1   0      0
1995 2   2      2
1995 2   1      1
Problem with `mutate()` column `h97`.
i `h97 = with(df, ave(h97, sj, hid, FUN = sum))`.
i `h97` must be size 2104 or 1, not 29494.
i The error occurred in group 1: sj = 1995.

It works with my other columns usaully, but not with this one. I looked up the question and repsonds in this link, Error: Problem with `mutate()` column (...) must be size 15 or 1, not 17192, and checked the variable h97, there is no NA or NaN. I also don't find any variables with 2104. What can possibly cause this error message, where can size 2104 come from, and how should I solve this problem?

MicL
  • 67
  • 1
  • 8
  • 2
    Since you are using `dplyr` why not `... group_by(...) %>% mutate(h97 = sum(...))` – Sotos Jan 12 '22 at 09:18
  • 2
    Good point! Thanks, it works now. But I'm still curious about the reason that causes this problem. – MicL Jan 12 '22 at 09:25
  • 2
    Please provide your data.frame with `dput` to create a reproducible example (s. https://stackoverflow.com/help/minimal-reproducible-example for further guidelines) – JKupzig Jan 12 '22 at 09:36

0 Answers0