I am looking for a smarter way to create this type

2019-08-20 03:55发布

问题:

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:

  1. To use loop:

mat as your dataset name

for (i in 1:length(colnames(mat))){
  colnames(mat)[i] <- paste0("Comp", i, sep=" ")
}
  1. You can also use dplyr::select() to rename colnames:

    dplyr::select(mat, Comp1 = colname1, Comp2 = colname2,...)



标签: r for-loop names