I am looking for a smarter way to create this type of name vectors in r:

我与影子孤独终老i 提交于 2019-12-11 14:47:17

问题


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,...)



来源:https://stackoverflow.com/questions/47436639/i-am-looking-for-a-smarter-way-to-create-this-type-of-name-vectors-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!