在R字符串变量中命名列显示空白

时间:2015-09-03 21:20:21

标签: r

如果之前已经提出这个问题但是我无法找到任何问题,请提前道歉。

现在,我尝试从文件中获取某些列,并将列命名为这些文件的名称。我以前做过,而且我知道它并不太难,但我遇到了很多麻烦。我的代码如下(所有文件在代码中早先声明为该目录中的所有文件)

    makelist<-function(list_text){
  if (list_text == "squared_median " || list_text == "squared_median_ranked"
      || list_text == "value_median " || list_text == "value_median_ranked")
    metric = "median"
  else
    metric = "avg"
  currfiles=allfiles[grepl(list_text,allfiles)]
  currfile=currfiles[1]
  currtable=read.table(currfile, header=T, sep='\t',stringsAsFactors = F)
  a<-cbind(gene=currtable[,1],paste0(currfile)=currtable[,metric])
  #col.name(a[,ncol(a)])<-currfile
  #names(a)[ncol(a)]<-as.character(currfile)
  for(currfile in currfiles[2:length(currfiles)])
  {
    currtable=read.table(currfile, header=T, sep='\t', stringsAsFactors=F)
    if (length(currtable[,metric]) > length(a[,1]))
     apply(a,2, function(x) length(x) = length(currtable[,metric]))

    a=cbind(a, "gene"=currtable[,1],currfile=currtable[,metric])
    #names(a)[ncol(a)]<-paste(currfile)
  }
  #names(a)=c("gene", currfiles[1], "gene", currfiles[2],"gene", currfiles[3],"gene", currfiles[4])
  write.table(a, paste(output_folder, list_text,".txt"),sep='\t',quote=F,row.names=F)
}

基本上,我传入的字符串用于从目录中收集某些文件。从那里开始,代码从该文件中获取中值或平均值,并将列命名为从中获取该信息的文件。我尝试了许多不同的方法但没有成功。注释方式是不起作用的方式 - 要么将列名留空,要么将其命名为文字变量名&#34; currfile&#34;而不是它包含的文件名。我已经离开了用

单独重命名所有列
names(a)=c("gene", currfiles[1], "gene", currfiles[2]...currfiles[n])

这只列出了所有其他列currfiles。

你能帮我辨别出错吗?我已经尝试将名称设置为get(currfile),并且不会让我运行脚本。

这些行

#col.name(a[,ncol(a)])<-currfile
#names(a)[ncol(a)]<-as.character(currfile)

给我留下了空白列名。

**作为旁边,if语句有关长度的行应该将每列的长度扩展到最新的最长列,但似乎不起作用。这可能是我还会读到的其他内容。

感谢您的帮助, 麦克

1 个答案:

答案 0 :(得分:0)

要设置表格的列名,请使用colnames(table)ref)。

在您的情况下,我希望colnames(a)[-1] <- currfile能够做到这一点,如果我当前理解您想要使用变量{中的字符串命名表a的最后一列{1}}。

相关问题