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

在R中标准化数据框数值变量时保留因子变量的技术问询

解决R中标准化数值变量同时保留因子变量的问题

Hey there! I totally get why your factor variable APPL_SITE_NONSITE got dropped—likely your previous code was only selecting numeric/integer columns and overwriting the entire data frame, leaving out non-numeric types. Let's use a straightforward for loop with if/else logic to fix this, so we keep your factor variable intact while standardizing the numeric ones.

Step-by-Step Solution Code

First, we'll work with a copy of your data frame to avoid messing up the original dcc:

# Create a copy of your data frame to preserve the original
dcc_scaled <- dcc

# Loop through each column in the data frame
for (col_name in colnames(dcc_scaled)) {
  # Check if the column is numeric or integer type
  if (is.numeric(dcc_scaled[[col_name]]) || is.integer(dcc_scaled[[col_name]])) {
    # Standardize: (value - mean) / standard deviation
    col_mean <- mean(dcc_scaled[[col_name]], na.rm = TRUE)
    col_sd <- sd(dcc_scaled[[col_name]], na.rm = TRUE)
    dcc_scaled[[col_name]] <- (dcc_scaled[[col_name]] - col_mean) / col_sd
  } else {
    # Leave non-numeric/factor columns as they are
    next
  }
}

What This Does

  • Preserves Original Data: By working on dcc_scaled (a copy), we don't alter your original dcc data frame—always a good practice!
  • Targeted Standardization: The if statement checks if a column is numeric or integer. Only those columns get the (value - mean)/sd treatment.
  • Keeps Factor Variables: The else clause uses next to skip over non-numeric columns (like your APPL_SITE_NONSITE factor), so they stay in the data frame untouched.
  • Robust to NAs: We added na.rm = TRUE to mean() and sd() just in case—even though you said you filtered complete observations, this prevents errors if any sneaky NAs are left.

Verify the Result

Run this to check that your factor variable is still there and numeric columns are scaled:

# Check variable types
str(dcc_scaled)

# Check summary stats of a scaled numeric column (mean ~0, sd ~1)
summary(dcc_scaled$your_numeric_column_here)

Bonus: Alternative (No Loop)

If you ever want a more concise approach without loops, you can use dplyr (but since you asked for loops, this is just extra):

library(dplyr)
dcc_scaled <- dcc %>%
  mutate_if(is.numeric, ~(.x - mean(.x, na.rm = TRUE)) / sd(.x, na.rm = TRUE))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:57:28