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

如何编写R函数优化多变量标准化并新增列的重复操作?

Create a Reusable Function to Scale Variables & Append to Your Data Frame

I totally get the pain of repeating scale() calls over and over—let's build a clean, flexible function that handles this in one go. This function will take your data frame, a list of variables to process, and automatically append scaled/centered versions with a clear suffix (like _scaled) to avoid cluttering your original data.

Here's the Custom Function

scale_and_append <- function(data, vars, suffix = "_scaled", center = TRUE, scale = TRUE) {
  # Check if all specified variables exist in the data frame
  missing_vars <- setdiff(vars, colnames(data))
  if(length(missing_vars) > 0) {
    stop(paste("Variables not found in data frame:", paste(missing_vars, collapse = ", ")))
  }
  
  # Iterate over each variable, scale it, and add to the data frame
  for(var in vars) {
    new_col_name <- paste0(var, suffix)
    data[[new_col_name]] <- scale(data[[var]], center = center, scale = scale)
  }
  
  # Return the modified data frame
  return(data)
}

Let's Break Down the Parameters

  • data: Your input data frame (e.g., mtcars, your custom dataset)
  • vars: A character vector of variable names you want to scale (e.g., c("mpg", "disp", "hp"))
  • suffix: The suffix to add to the new scaled variables (default: _scaled—feel free to change to _centered if you only center)
  • center: Logical, whether to center the variable (mean = 0; default: TRUE)
  • scale: Logical, whether to scale the variable (standard deviation = 1; default: TRUE)

Example Usage

Let's test this with the built-in mtcars dataset:

# Load sample data
data(mtcars)

# Scale mpg, disp, and hp, append scaled columns to mtcars
mtcars_scaled <- scale_and_append(mtcars, vars = c("mpg", "disp", "hp"))

# Check the new columns
head(mtcars_scaled[, c("mpg", "mpg_scaled", "disp", "disp_scaled")])

Bonus: Adjust for Only Centering (No Scaling)

If you just want mean-centered variables (not standardized), set scale = FALSE:

mtcars_centered <- scale_and_append(mtcars, vars = c("wt", "qsec"), suffix = "_centered", scale = FALSE)

This function keeps your code DRY (Don't Repeat Yourself) and makes it easy to tweak scaling/centering behavior across all your variables at once.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:24:51