0

Here is some example data, df:

age_group class Value
   0-4      A     2
   0-4      A     1
   0-4      B     1
   5-9      A     2
   5-9      A     3
   5-9      B     1
   5-9      B     1
   9-14     A     1

I have been attempting to create a two way summary table -something like this:

   0-4 5-9 9-14
A   3   5   1
B   1   2   NA

I thought i had cracked it last night with:

tmp = with(df, tapply(Value), list(age_group, class), FUN=sum))

However when inspecting this table the numbers don't tie up with what i would expect.

Does anyone know what my tmptable actually represents? Also how would i get my desired result?

Thanks, John

Sotos
  • 47,396
  • 5
  • 31
  • 61
JDraper
  • 35
  • 2
  • 7
  • 1
    ? `aggregate()` https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family oder `xtabs(Value ~ class + age_group, data=df)` – jogo Feb 21 '18 at 10:02
  • Trying `tmp2 – JDraper Feb 21 '18 at 10:08
  • 1
    `with(df, tapply(Value, list(class, age_group), FUN=sum))` works for me. Are you getting an error? What doesn't work? – A5C1D2H2I1M1N2O1R2T1 Feb 21 '18 at 10:14
  • Why are you doing `as.numeric(as.character(S4.Data$Value))`? Is it a `factor` currently? It might be best to post a few lines of your actual data as a `dput`.... – A5C1D2H2I1M1N2O1R2T1 Feb 21 '18 at 10:18
  • @A5C1D2H2I1M1N2O1R2T1 `with(df, tapply(Value, list(class, age_group), FUN=sum))` is different from what i used : `tmp = with(df, tapply(Value), list(age_group, class), FUN=sum))`. The former produces a list of length 8, while the latter (at least for me anyway). Yes my data is a factor which is why i have to convert to char and then num. – JDraper Feb 21 '18 at 10:57
  • @JDraper, What you've posted in your comment shouldn't even work.... – A5C1D2H2I1M1N2O1R2T1 Feb 21 '18 at 11:00
  • @A5C1D2H2I1M1N2O1R2T1 this code? `with(df, tapply(Value), list(age_group, class), FUN=sum))` Also sorry i can't post the data for confidentiality reasons. If it helps Value is a factor (which gets converted to numeric), Org.Name is a factor and Measure_desc is a character. – JDraper Feb 21 '18 at 11:13
  • @JDraper, yes. How can you do `tapply(Value)`? – A5C1D2H2I1M1N2O1R2T1 Feb 21 '18 at 11:15
  • @A5C1D2H2I1M1N2O1R2T1 my code when using `tapply` (which doesn't throw out an error): `with(S4.Data, tapply(as.numeric(as.character(Value)), list(Org.Name, Measure_Desc), FUN=sum)))` – JDraper Feb 21 '18 at 11:17

0 Answers0