在R语言中排除不符合调研要求的数据集样本
Hey there! Excluding records where participants are too young or old is a routine data cleaning step in R, and there are two go-to methods that’ll get the job done quickly. Let’s break them down using a common example: suppose your dataset is named survey_data and the age column is called age, and you want to keep only participants aged 18 to 65 (adjust the numbers to match your specific requirements).
Method 1: Base R Indexing
This is great if you don’t want to load any extra packages. Use logical conditions to subset your data directly:
# Keep records where age is between 18 and 65 (inclusive) clean_data <- survey_data[survey_data$age >= 18 & survey_data$age <= 65, ] # Alternatively, exclude records where age is outside the range clean_data <- survey_data[!(survey_data$age < 18 | survey_data$age > 65), ]
- The
&operator means "and", so we’re requiring both conditions to be true. - The
!operator negates the condition, so we’re keeping everything not in the excluded age groups.
Method 2: Using dplyr (Tidyverse Style)
If you prefer cleaner, more readable code (especially for complex data pipelines), the dplyr package is your friend. First install it if you haven’t already, then use the filter() function:
# Install dplyr if needed (run once) install.packages("dplyr") # Load the package library(dplyr) # Filter for eligible ages (comma acts as "and") clean_data <- survey_data %>% filter(age >= 18, age <= 65) # Even shorter: use the `between()` function (inclusive of bounds) clean_data <- survey_data %>% filter(between(age, 18, 65))
- The pipe operator
%>%passes the dataset into thefilter()function, making the code read like a sentence. between()is a handy shortcut for range checks—just pass the column, lower bound, and upper bound.
Quick Check to Verify
After filtering, double-check that you’ve removed all ineligible records with a quick summary:
# View summary stats for the cleaned age column summary(clean_data$age) # Confirm no excluded ages remain (should return 0) sum(clean_data$age < 18 | clean_data$age > 65)
内容的提问来源于stack exchange,提问作者Anna Cruz

