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

R入门求助:如何基于COPD与emphysema2创建均值变量lung.disease

Hi there! Welcome to R—great to help you get started with creating your new variable. Let's walk through two simple ways to calculate the mean of COPD and emphysema2 into a new column called lung.disease.

Method 1: Base R (no extra packages needed)

If you prefer using R's built-in functions without installing anything, you can use rowMeans() to compute the mean across rows for your target columns. This method also handles missing values (NA) if you add the na.rm = TRUE argument:

# Replace 'df' with the actual name of your data frame
df$lung.disease <- rowMeans(df[, c("COPD", "emphysema2")], na.rm = TRUE)
  • df[, c("COPD", "emphysema2")] selects just the two columns you want to average
  • rowMeans() calculates the mean row-by-row
  • na.rm = TRUE ensures that if one of the values is NA, it still computes the mean using the available value (remove this if you want NA to propagate instead)

Method 2: Using dplyr (tidyverse style)

If you're planning to do more data cleaning or manipulation later, the dplyr package from the tidyverse makes this syntax more readable. First, install and load the package if you haven't already:

install.packages("dplyr") # Only run this once
library(dplyr)

Then use mutate() to add the new column. You can either calculate the mean directly or use rowMeans() with across() to handle NAs:

# Option 1: Simple mean calculation (returns NA if either value is NA)
df <- df %>%
  mutate(lung.disease = (COPD + emphysema2) / 2)

# Option 2: Handle missing values gracefully
df <- df %>%
  mutate(lung.disease = rowMeans(across(c(COPD, emphysema2)), na.rm = TRUE))

Testing with your sample data

If you use the sample data you provided, running either method will give you lung.disease values of 0.309, 0.309, 0.309, 0, 0—which makes sense since all COPD values are 0, so the mean is just half of emphysema2.

Let me know if you run into any issues or have more questions as you learn R!

内容的提问来源于stack exchange,提问作者Mikey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:32:58