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

如何在R语言中用循环按列名索引删除E1_3至E128_3列?

Fixing the Column Deletion Loop in R

Hey Riccardo, I’ve dealt with this exact frustration before—let’s break down why your loop isn’t working and how to fix it quickly.

Why Your Original Code Fails

The issue is with how you’re trying to reference the column names dynamically. When you write data_wide$E[i]_3, R interprets E[i]_3 as a literal column name (not a dynamically generated one like E1_3). The $ operator only works with fixed, literal column names, so it can’t parse the [i] part to create the correct name.

Working Solutions

1. Fixed Loop Approach

Rewrite your loop to first generate the correct column name as a string, then use the [[ operator (which accepts string inputs) to remove the column:

for(i in 1:128) {
  # Create the exact column name (e.g., "E1_3", "E2_3")
  target_col <- paste0("E", i, "_3")
  # Remove the column using string indexing
  data_wide[[target_col]] <- NULL
}

2. Vectorized (No Loop) Approach (More Efficient)

For better performance and cleaner code, you can generate all the column names at once and remove them in one step—no loop needed:

# Generate all column names to remove
cols_to_drop <- paste0("E", 1:128, "_3")

# Base R method
data_wide <- data_wide[, !names(data_wide) %in% cols_to_drop]

# If you use tidyverse/dplyr:
library(dplyr)
data_wide <- data_wide %>% select(-all_of(cols_to_drop))

This method is faster, especially with large datasets, and avoids the overhead of a loop.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 09:17:28