代码之家  ›  专栏  ›  技术社区  ›  Cisco

向数据表示函数添加新循环时出现问题

  •  1
  • Cisco  · 技术社区  · 6 年前

    我有一个工作数据集:

    chr<-c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2)
    iid<-c("sc1","sc1","sc2","sc2","sc3","sc3","sc4","sc4","sc5","sc5","sc1","sc2","sc3","sc4","sc5","sc6")
    pos1<-c(2,34,7,56,12,67,11,34,2,67,23,56,12,11,12,43)
    pos2<-c(23,54,12,98,54,79,22,67,43,98,23,54,65,32,54,57)
    fam<-c(1,1,1,1,2,2,2,2,3,3,1,2,3,4,5,6)
    data<-data.frame( iid,chr,pos1,pos2,fam)
    

    我的意图是表示每个IID的data$pos1和data$pos2之间的部分。我使用以下脚本由chr完成:

    plot_chr<-function(f,descn,chr){
      a<-f[f$chr==chr,]
      iids_num<-as.character(unique(a$iid))
      nsamps<-length(iids_num)
      xlimi<-c(0,max(a$pos2))
      plot(NULL,xlim=xlimi,ylim=c(0,nsamps),main=descn,xlab="Physical Position",ylab="Subject")
      for (id_no in 1:nsamps) {
        plot_dat<-a[which(a$iid==iids_num[id_no]),]
        if (length(plot_dat$iid) > 0) {
          for (roh_n in 1:length(plot_dat$iid)) {
            x<-c(plot_dat[roh_n,"pos1"],plot_dat[roh_n,"pos2"])
            y<-  c(id_no,id_no)
            lines(x,y,lw=2,lend=2,col="red")
          }
        }
      }
      return(a)
    }
    

    结果如下:

    windows()
    plot_chr(data,"data",1)
    

    enter image description here

    但是,我想修改并添加一个新变量。在这个精确的绘图(chr=1)中,我想根据因子数据$fam更改线条的颜色。例如,我想要iid=sc1和sc2(fam=1)的红线,iid=sc3和sc4(fam=2)的蓝线,iid=sc5(fam=3)的绿线。每次尝试修改脚本时,都会出现错误。

    1 回复  |  直到 6 年前
        1
  •  2
  •   digEmAll    6 年前

    可以使用命名向量定义颜色映射:

    plot_chr<-function(f,descn,chr,colorsByFam){
      a<-f[f$chr==chr,]
      iids_num<-as.character(unique(a$iid))
      nsamps<-length(iids_num)
      xlimi<-c(0,max(a$pos2))
      plot(NULL,xlim=xlimi,ylim=c(0,nsamps),main=descn,xlab="Physical Position",ylab="Subject")
      for (id_no in 1:nsamps) {
        plot_dat<-a[which(a$iid==iids_num[id_no]),]
        if (length(plot_dat$iid) > 0) {
          for (roh_n in 1:length(plot_dat$iid)) {
            x<-c(plot_dat[roh_n,"pos1"],plot_dat[roh_n,"pos2"])
            y<-  c(id_no,id_no)
            # here we're getting the color corresponding to fam
            # note that as.character is necessary, otherwise it will use plot_dat$fam
            # as index of colorsByFam vector and not as a name
            color <- colorsByFam[as.character(plot_dat$fam)] 
            lines(x,y,lw=2,lend=2,col=color)
          }
        }
      }
      return(a)
    }
    
    colorsByFam <- c('1'='red','2'='blue','3'='green')
    # or equivalently : 
    # colorsByFam <- c('red','blue','green')
    # names(colorsByFam) <- c(1,2,3)
    plot_chr(data,"data",1,colorsByFam)
    

    结果:

    enter image description here