Reputation: 3
I'm having a problem with changing colnames of one of my matrixes. I need to change the name of columns 1,5,9,.. which makes a progression of numbers by 4. I run the following code but I have no idea why the colnames won't change.
> a=seq(1,72,by=4)
> cols= paste("cancer",a)
> colnames(lcne[,a]) = cols
Does anyone know what I am doing wrong and how I can fix it?
Upvotes: 0
Views: 30
Reputation: 887118
We can also use rename_at
library(dplyr)
newnames <- c('a', 'b', 'c')
mtcars <- mtcars %>%
rename_at(c(1, 3, 5), ~ newnames)
names(mtcars)
#[1] "a" "cyl" "b" "hp" "c" "wt" "qsec" "vs" "am" "gear" "carb"
Upvotes: 0
Reputation: 1085
First make a vector with the actual colnames. Then replace the desired ones in the vector and add the whole vector back to the matrix.
nameVec <- names(lcne)
nameVec[a] = cols
colnames(lcne) <- nameVec
Upvotes: 0
Reputation: 2301
colnames indexes are referenced outside the function. E.g.:
newnames <- c('a', 'b', 'c')
colnames(mtcars)[c(1, 3, 5)]
[1] "mpg" "disp" "drat"
colnames(mtcars)[c(1, 3, 5)] <- newnames
colnames(mtcars)
[1] "a" "cyl" "b" "hp" "c" "wt" "qsec" "vs" "am" "gear" "carb"
Upvotes: 1