survey_report.R in R
Clean a survey data frame and report grouped results in base R.
#!/usr/bin/env Rscript
# Clean a small survey data frame and report grouped results in base R.
survey <- data.frame(
respondent = 1:8,
region = c("north", "south", "north", "east",
"south", "east", "north", NA),
rating = c(4, 5, NA, 3, 5, 2, 4, 4),
minutes = c(12, 25, 18, 7, 31, 9, 22, 14),
stringsAsFactors = FALSE
)
clean <- survey[!is.na(survey$region) & !is.na(survey$rating), ]
clean$region <- factor(clean$region,
levels = c("north", "south", "east"))
clean$engaged <- clean$minutes > 15
cat("responses:", nrow(survey), "->", nrow(clean), "after cleaning\n\n")
by_region <- aggregate(cbind(rating, minutes) ~ region,
data = clean, FUN = mean)
by_region$rating <- round(by_region$rating, 2)
by_region$minutes <- round(by_region$minutes, 1)
print(by_region)
cat("\nengagement by region:\n")
print(table(clean$region, clean$engaged))
cat("\noverall mean rating:", round(mean(clean$rating), 2), "\n")
cat("correlation rating~minutes:",
round(cor(clean$rating, clean$minutes), 3), "\n")
How it works
- Rows with missing region or rating are dropped.
factororders regions; a derived column flags engagement.aggregateandtableproduce the grouped report.
Keywords and builtins used here
aggregateccatcbindcorfactormeannrowprintroundtable
The run, in numbers
- Lines
- 31
- Characters to type
- 994
- Tokens
- 272
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 155 seconds.
Step 1 of 1 in Encore, step 8 of 8 in Data frames in base R.