1

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)

1 Answer 1

5

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Can't believe I didn't think of that.
It's a subtle but important difference. colnames(df[, 3:7]) = "names of columns in the subset of df containing columns 3-7. colnames(df)[3:7] = "names of columns 3-7 in the set of all column names from df".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.