如何在R语言中用循环按列名索引删除E1_3至E128_3列?
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

