In R, using dplyr, I have a data table that has independent variables sex and po
ID: 3883688 • Letter: I
Question
In R, using dplyr, I have a data table that has independent variables sex and political party, and dependent variable salary. I can find the average salary of men/women and of Labour vs Tory, but I want the average of Tory men, Tory women, Labour men and Labour women. How can I get that?
I have:
Labour Tory
Male Female Male Female
£30,000 £27,000 £25,000 £23,000
£26,000 £19,000 £24,500 £27,000
£28,000 £23,000 £26,000 £21,000
£35,000 £22,000 £31,000 £22,000
£35,000 £21,000 £27,000 £30,000
£37,000 £20,000 £30,000 £30,000
I need something like:
gender party mean(salary)
1 female labour 27833.33
2 female tory 23000.00
3 male labour 27250.00
4 male tory 31166.67
Explanation / Answer
To build a function, complete data set is needed.Here, you can use aggregate function.
It is comparitively easy to collapse the data utilizing one or more BY variables and a specific function.
aggdata <-aggregate (data = df, salary~gender+party, FUN = mean)
print(aggdata)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.