在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 originaldccdata frame—always a good practice! - Targeted Standardization: The
ifstatement checks if a column is numeric or integer. Only those columns get the (value - mean)/sd treatment. - Keeps Factor Variables: The
elseclause usesnextto skip over non-numeric columns (like yourAPPL_SITE_NONSITEfactor), so they stay in the data frame untouched. - Robust to NAs: We added
na.rm = TRUEtomean()andsd()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

