问题
I am looking for a smarter way to create this type of name vectors in r (rmarkdown).
I have:
# 'mat' is a matrix with 10 columns
colnames(mat)<-c("Comp 1","Comp 2","Comp 3", "Comp 4", "Comp 5","Comp 6"
,"Comp 7","Comp 8", "Comp 9", "Comp 10")
Ideally I would do something with a for loop;
for i =1:10
colnames(mat)<- c("comp 'i'")
but this doesn't work. How can i do this?
Thanks' in advance!
回答1:
- To use loop:
mat
as your dataset name
for (i in 1:length(colnames(mat))){
colnames(mat)[i] <- paste0("Comp", i, sep=" ")
}
You can also use
dplyr::select()
to rename colnames:dplyr::select(mat, Comp1 = colname1, Comp2 = colname2,...)
来源:https://stackoverflow.com/questions/47436639/i-am-looking-for-a-smarter-way-to-create-this-type-of-name-vectors-in-r