0
unemp <- read_excel("/Users/wathiq/Downloads/laucntycur14.xlsx")
sub.unemp <- subset(unemp,select = c(State,countyState,Unemployment))
fl.unemp = sub.unemp[sub.unemp[,1]=="12",]
unique(fl.unemp$countyState)
fl.unemp2 <- subset(fl.unemp, select = c(countyState,Unemployment))
attach(fl.unemp)
fl.sort2 <- fl.unemp2[order(countyState), ]

So, I have a dataframe that has the unemployment rate for each county in Florida and I want to find the average unemployment rate per county. How do I go about that?

Just to give you an idea, fl.sort2 is a dataframe with 2 columns, the name of the county and the unemployment rate. I sorted them alphabetically

County                ..................Unemployment
Alachua County, FL    4.3
Alachua County, FL    3.0
Alachua County, FL    2.3
Baker County, FL      4.5
Baker County, FL      4.1

How would I find the mean unemployment for each county?

Edgar Santos
  • 3,426
  • 2
  • 17
  • 29
warhol
  • 21
  • 6
  • Please, provide a reproducible example. – Edgar Santos May 03 '17 at 04:27
  • You could use the aggregate() function. For instance, aggregate(data$Unemployment, list(data$County), mean) – Edgar Santos May 03 '17 at 04:35
  • `library(dplyr); fl.unemp %>% group_by(County) %>% summarise(County_Mean = mean(Unemployment))`. The data frame does not need to be sorted for this to work. If other states are in your data frame and you want it by State and County, then, `unemp %>% group_by(State, County) %>% summarise(County_Mean = mean(Unemployment))` – eipi10 May 03 '17 at 05:31

1 Answers1

1

There are a bunch of options. They all give the same result.

First

avg.unemp <- tapply(fl.sort2$Unemployment, fl.sort2$countyState, mean, na.rm=T)
avg.unemp

Second

avg.unemp<- aggregate(Unemployment~countyState, data = fl.sort2, mean, na.rm=T)
avg.unemp

Third

library(data.table)
setDT(fl.sort2)
fl.sort2[,avg.unemp:= mean(Unemployment, na.rm=T), by=countyState]
fl.sort2 # result should be in 3rd column named "avg.unemp"

Feel free to skip the na.rm=T part if you don't have NAs.

Yannis Vassiliadis
  • 1,719
  • 8
  • 14