Rscript -e 'df <- read.csv("data.csv"); print(tapply(df$salary, df$dept, mean))'

Category: Data Science & Analysis

Rscript -e 'df <- read.csv("data.csv"); print(tapply(df$salary, df$dept, mean))'

Average salary per dept with tapply

tapply applies a function to groups of a vector: here it splits df$salary by the df$dept factor and computes the mean within each group, a group-by operation. The dollar sign syntax selects a column from the data frame df. The result is a named vector of per-department averages. This is base R's answer to SQL GROUP BY without loading extra packages.
Looking for more? Search all 7,657 commands — works offline, in English or Spanish, and fixes typos.