You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Incorrect replace() syntax: The replace() function needs three clear arguments: the vector to modify, the condition for which elements to replace, and the new value. Your current code replace(value=88, 0) doesn't specify which column to change or the matching condition, so it never actually modifies the menthlth values at all.
  2. 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 the menthlth column, uses the condition menthlth == 88 to 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 of mutate() gives us a single row with the average value, which is exactly what you need. The na.rm = TRUE argument ensures any missing values in menthlth don'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:32:33