Stonecraft
Stonecraft

Reputation: 814

replace substring in subset of column names in R

I have a dataframe where I want to replace a subset of the columns with new names created by prepending an identifier to the old one. For example, to prepend columns 3:7 with the string, "TEST", I tried the following.

What am I missing here?

# Make a test df
df <- data.frame(replicate(10,sample(0:1,100,rep=TRUE)))

#Subsetting works fine
colnames(df[,3:7]) 

#sub works fine
sub("^", "TEST.", colnames(df[,3:7]))

#replacing the subset of column names with sub does not
colnames(df[,3:7]) <-  sub("^", "TEST.", colnames(df[,3:7]))
colnames(df)

#Also doesn't work
colnames(df[,3:7]) <-  paste("TEST.", colnames(df[,3:7]), sep ="")
colnames(df)

Upvotes: 1

Views: 1697

Answers (1)

neilfws
neilfws

Reputation: 33812

The column names should be a vector, with the indices outside of the parentheses:

colnames(df)[3:7] <-  sub("^", "TEST.", colnames(df)[3:7])

You could also:

colnames(df)[3:7] <-  paste0("TEST.", colnames(df)[3:7])

Upvotes: 5

Related Questions