RayX500
RayX500

Reputation: 267

In R: How to delete specific string in specific column names

Data Cleaning Task

I have a data frame df with 1000 columns, with each column name starting with X_. I want to delete X_ in only the first 30 columns.

X_col1,X_col2,X_col3,X_col4,X_col5,.....,X_col1000.

Desired output:

col1,col2,col3,col4,col5,col6,.....,col30 ; X_col31, X_col32,.....,X_col1000

X_ should be removed in X_col1 to X_col30 ONLY while leaving X_col31 to X_col1000

Attempt in R

names(df) <- gsub("X_", "", names(df)) # this removes `X_` in all 1000 columns, I only want the first 30 columns

Thanks

Upvotes: 2

Views: 394

Answers (1)

Shawn Brar
Shawn Brar

Reputation: 1420

This would do, i think

colnames(df)[1:30] <- gsub("X_", "", colnames(df)[1:30])

Upvotes: 1

Related Questions