-1

I am trying to group data in R by Education-Experience-Year cells. My search led me to the dplyr package, and I can use code like this

by_EdExpT <- df1 %>% group_by(ED, EXP, YEAR)

to group the data. But I'm not really sure how to perform operations on it. Is dplyr the best package to use for this, and how do I perform operations like means or regressions?

neilfws
  • 32,751
  • 5
  • 50
  • 63

1 Answers1

0

It really depends on what you mean by perform operations. You can use the summarise() function from dplyr to compute means by group, for example. It'll work for anything that produces one output per group.

summarise(by_EdExpT, mean)

If you want some overview of dplyr functionalities you can use the cheatsheet to check it out.

mutate() can include summary statistics to your original data, as an example:

iris %>% group_by(Species) %>% mutate(avg = mean(Sepal.Length))

will add the avg column, that represents the average Sepal.Length for the Species corresponding the observation in each row.

VFreguglia
  • 2,129
  • 4
  • 14
  • 35
  • This cheatsheet is very helpful, thank you. So, if I do: `df1 %>% group_by(ED, EXP, YEAR) %>% summarize(AvgW = mean(INCWAGE))`, I get a table with the average wage by group, but what I really want is that to be added to my dataframe as a variable. The mutate command doesn't seem to do that, how do I accomplish this? – user10610530 Nov 05 '18 at 23:50
  • Can you add a minimal reproducible example to your question? You can use the function `dput()` to include (a piece of) your data set. – VFreguglia Nov 06 '18 at 00:04
  • Also, this question might be helpful: https://stackoverflow.com/questions/6053620/calculate-group-mean-or-other-summary-stats-and-assign-to-original-data – VFreguglia Nov 06 '18 at 00:04
  • I followed your edit to the main answer and it worked. Thanks so much there. One last thing, I've been trying `df1 %>% ungroup()` to undo the grouping and it seems to be failing, what other arguments do I need to include? I copied the documentation. – user10610530 Nov 06 '18 at 03:45