0

I am trying to calculate mean salary for every job title from a data set which has 2159 job titles and convert into a list. My code

> for (i in 1:length(unique(sfs$JobTitle))) {
  a<-print(paste((sfs$JobTitle[[i]])))
  b<-print(paste((mean(sfs$BasePay[[i]]))))
  ms<-list(a,b)
}

Also tried

for (i in 1:length(unique(sfs$JobTitle))) {   ms<-matrix((sfs$JobTitle[[i]]),(mean(sfs$BasePay[[i]]))) }

The output I am getting is a list of 2 elements only. Can you guys help. Thanks

marbel
  • 7,560
  • 6
  • 49
  • 68
mezz
  • 427
  • 2
  • 5
  • 10
  • and that output you are getting is for the last two only. If you are looking for mean salary of all job titles, show us your data `head(dput(dataframename)`, there are faster ways out there – CuriousBeing Feb 20 '16 at 22:35
  • Seems like you need `aggregate(sfs$BasePay, list(sfs$JobTitle), mean)`.. but other than that, there are a lot of mistakes in your code. You don't have to use `paste` or `print` or `[[`. – slamballais Feb 20 '16 at 22:41

1 Answers1

0

Perhaps you don't need a for loop. There are other ways to do it. If you have a data.frame try this:

agg = aggregate(BasePay ~ JobTitle, data=sfs, mean)

This would work also:

sapply(split(sfs$BasePay, sfs$JobTitle), mean)

If you insist on having a list, use lapply:

lapply(split(sfs$BasePay, sfs$JobTitle), mean)
marbel
  • 7,560
  • 6
  • 49
  • 68