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

R 向数据表示函数添加新循环时出现的问题,r,loops,plot,R,Loops,Plot,我有一个工作数据集: 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,

我有一个工作数据集:

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)


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

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

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)
plot\u chr
windows()
plot_chr(data,"data",1)
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)