As an alternative solution, you could use gsub()
to replace all the "state." with nothing (""), here showing that with just a vector:
gsub("state.", "", c("state.abb", "state.area", "state.division", "state.region"))
To replace the colnames names:
colnames(df) <- gsub("state.", "", colnames(df))
As a bonus, imagine you want to replace a word or string that occurs in some but not all of your columns. Taking the built in iris dataset as an example, you could replace "Petal" with "P" for the columns where "Petal" is in the column name with the exact same approach:
colnames(iris) <- gsub("Petal", "P", colnames(iris))
I wouldn't bother with a for loop for this job, it's far easier to use a vectorised approach. But to explain your error, when you did colnames(df[1])
you were returning the column name of a single column dataframe that you had isolated from your main dataframe, rather than handling the main dataframe itself. For example, iris[1]
returns a dataframe with one column - see str(iris[1])
- so colnames(iris[1])
returns the column name of that isolate. A slight change instead allows you to return (and then change) the 1st element of the vector of column names for iris: colnames(iris)[1]
.