Subsetting with loops

Jake

I am new to R and am trying to figure out a way to subset my dataset without writing a line of code for each subset. My dataset has multiple years and I am trying to subset each year out. The column "Year" has 5 different years 2017,2016,2015,2014,2013. What I currently did is this(dataset is my raw data):

Year17 <- dataset[dataset$Year=="2017",]
Year16 <- dataset[dataset$Year=="2016",]
Year15 <- dataset[dataset$Year=="2015",]
Year14 <- dataset[dataset$Year=="2014",]
Year13 <- dataset[dataset$Year=="2013",]

I think there is some way to loop this through but I have not been able to figure out how.

I then am also looking for a way to extract the quartile, mode, median, and standard deviation. I currently do it with this:

Year17Finance <- quantile(Year17$Financials, probs= c(0.10, 0.25, 0.50, 0.75, 0.90), na.rm = T)
Year17Sales <- quantile(Year17$Sales, probs= c(0.10, 0.25, 0.50, 0.75, 0.90), na.rm = T)
mean(Year17$Financials, na.rm = T)
median(Year17$Financials,na.rm = T)
sd(Year17$Financials, na.rm = T)

My end goal is to be able to upload the data file and run it through the code and it then shoots out the quartile, mean, median, and standard deviation for a given variable.

Any guidance would be greatly appreciated.Thanks

Scott Ritchie

I assume you are creating each subsetted data frame so you can calculate the summary statistics for each year? For this type of problem I like the data.table package, which enables you to split calculations across a group column:

library(data.table)
dataset <- as.data.table(dataset)

financial_summary_stats <- dataset[, list(
    q10 = quantile(Financials, 0.10, na.rm=TRUE),
    q25 = quantile(Financials, 0.25, na.rm=TRUE),
    q50 = quantile(Financials, 0.50, na.rm=TRUE),
    mean = mean(Financials, na.rm=TRUE),
    q75 = quantile(Financials, 0.75, na.rm=TRUE),
    q90 = quantile(Financials, 0.90, na.rm=TRUE)
  ), by = Year]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related