R语言中修改多观测值取值问题:替换特定值以计算宾夕法尼亚州心理健康不佳日均值
Fixing Your R Code for Mental Health Day Average Calculation
Hey there! Let's work through why your code isn't replacing the 88 values and how to get the correct average for Pennsylvania's mental health days.
What's Wrong With the Original Code?
Your mutate() call has two key issues:
- Incorrect
replace()syntax: Thereplace()function needs three clear arguments: the vector to modify, the condition for which elements to replace, and the new value. Your current codereplace(value=88, 0)doesn't specify which column to change or the matching condition, so it never actually modifies thementhlthvalues at all. - Calculating the mean too early: You're trying to compute the average in the same
mutate()step where you (attempt to) replace values. Even if the replacement worked, this would repeat the mean across every row instead of giving a clean, single summary value.
Correct Code
Here's the revised version that properly replaces 88 with 0 and calculates the correct average:
avgMHNotGoodPenn <- brfss2 %>% filter(state == '42') %>% # First filter to only Pennsylvania data mutate(menthlth = replace(menthlth, menthlth == 88, 0)) %>% # Replace 88 with 0 in menthlth summarise(avgMHNotGood = mean(menthlth, na.rm = TRUE)) # Calculate the average, ignoring NA values
Breakdown of the Fixes
- Filter first: We narrow down to Pennsylvania (
state='42') right away to reduce the data we're processing, which is more efficient and keeps things focused. - Proper replacement: The
mutate()line explicitly targets thementhlthcolumn, uses the conditionmenthlth == 88to identify which values to swap, and sets them to 0—this ensures all "zero days" are correctly coded. - Summarize for the mean: Using
summarise()instead ofmutate()gives us a single row with the average value, which is exactly what you need. Thena.rm = TRUEargument ensures any missing values inmenthlthdon't break the mean calculation.
After running this code, avgMHNotGoodPenn will hold the correct average number of poor mental health days for Pennsylvania, with all 88 values properly replaced by 0.
内容的提问来源于stack exchange,提问作者sfroehle
相关产品推荐
相关产品推荐

