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

R语言循环计算权重生成新变量遇语法错误:unexpected '='

Fixing the R Syntax Error for Weighted Column Calculation

First, let's clarify your setup:

Original Dataset

A     B
0.8   0.9
0.99  0.88
0.7   0.9658
0.65  0.6684

Desired Output

You want to generate weighted combinations of columns A and B into new columns like A_10 (10% weight to A, 90% to B), A_20 (20% to A, 80% to B), etc., resulting in:

A     B       A_10      A_20      A_30      A_40      A_50
0.8   0.9     0.89      0.88      0.87      0.86      0.85
0.99  0.88    0.891     0.902     0.913     0.924     0.935
0.7   0.9658  0.93922   0.91264   0.88606   0.85948   0.8329
0.65  0.6684  0.66656   0.66472   0.66288   0.66104   0.6592

Your Attempted Code (With Error)

for (i in 10:90) { 
  df <- df %>% mutate(A_[i] =(A*[i]/100)+(B*((1-[i])/100))) 
}

Error Message

Error: unexpected '=' in:" df <- df %>% mutate(A_[i] ="


What's Causing the Error?

There are two key syntax issues here:

  1. Dynamic column naming: A_[i] is not a valid way to create dynamic column names in dplyr::mutate(). You need to use non-standard evaluation to assign names on the fly.
  2. Invalid variable reference: [i] is incorrect syntax for calling the loop variable i — you should just use i directly.

Fixed Code (Loop Approach)

Here's the corrected version of your loop that works as intended:

library(dplyr)

# First, define your original dataset properly
df <- tibble(
  A = c(0.8, 0.99, 0.7, 0.65),
  B = c(0.9, 0.88, 0.9658, 0.6684)
)

# Loop through weights (adjust range to 10:90 if you need all up to A_90)
for (i in seq(10, 50, 10)) {
  # Create dynamic column name (e.g., "A_10", "A_20")
  new_col <- paste0("A_", i)
  # Use !! and := to assign the dynamic column in mutate
  df <- df %>%
    mutate(!!new_col := A * (i/100) + B * ((100 - i)/100))
}

# View the final result
print(df)

Key Fixes:

  • paste0("A_", i) generates the correct column name string.
  • !!new_col := tells dplyr to evaluate new_col as the column name, instead of treating it as a literal string.
  • Fixed the weighted calculation: replaced [i] with i, and simplified (1 - i/100) to (100 - i)/100 for clarity (both are mathematically equivalent).

More Efficient Alternative (No Loop)

If you prefer a more idiomatic dplyr approach without loops, you can use purrr::map_dfc to generate all columns at once:

library(dplyr)
library(purrr)

# Define weights you want to use
weights <- seq(10, 50, 10)

df <- df %>%
  bind_cols(
    map_dfc(weights, function(w) {
      tibble(!!paste0("A_", w) := A * w/100 + B * (100 - w)/100)
    })
  )

This method is cleaner and avoids repeatedly reassigning df in a loop.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:25:34