如何解决使用清单中的for循环在R中产生多个图
我有一组数据,它是肝脏样品中6种不同细胞类型的种群。我想将这组数据与另一组属性进行比较-样本来源患者的遗传特征。因此,例如,基因1会有三种不同的变体,我需要制作一个箱形图,y轴上的细胞数,x轴上的细胞类型,每种细胞类型上都有三个箱形图,每个箱形图一个基因变异。我有一个脚本可以产生这种情况,但是如果我想检查细胞数量与基因2变异的比较情况,我必须重写脚本以将“ gene1”替换为“ gene2”。我希望脚本自动为所有基因绘制图形,而无需为每个基因重写它。我认为这样做的好方法是先列出基因,然后再进行for循环。 for循环将包含我之前的脚本,该脚本可以工作,并且对于列表中的每个项目,它都会生成一个图形。
以下是当前有效的方法,一次将其设置为一个:
# fetches all data from excel file
Alldata.Table = read_excel("E:/data/datafile.xlsx",sheet = "sheet1")
#selects cell number data,normalizes cell numbers to a reference cell number
celldata.Table.Normalized <- as.data.frame(apply(Alldata.Table[,c(34:39)],2,function(x) {x/Alldata.Table[,33]}))
colnames(celldata.Table.Normalized) <- colnames(Alldata.Table[,c(34:39)])
celldata.Table.Long <- pivot_longer(cell.Table.Normalized,cols = colnames(celldata.Table.Normalized))
#adds anonymous patient number to cell data,there are 6 cell types so each patient number is repeated 6 times.
#This information doesn't appear on the graph but I used it to check the data was being moved around correctly
#and the cell number results match the patient samples as they do in the original table
celldata.Table.Long$patient <- rep(Alldata.Table$`PatientNo`,each = 6)
#adds gene variant information
celldata.Table.Long$Gene1 <- rep(Alldata.Table$`Gene1`,each = 6)
#makes boxplot
q <- ggplot(celldata.Table.Long,aes(x = name,y = value,fill = Gene1)) +
geom_boxplot()+
xlab("Gene 1 variant")+
ylab("Relative proportions")+
theme_bw()
q + stat_compare_means(aes(group = Gene1),label.y = .5,label="p.signif")
这是我尝试在列表和for循环中添加基因变异信息的方法:
genelist <- list("Gene1","Gene2","Gene3")
for (i in seq_along(genelist)) {
celldata.Table.Long$genelist[i] <- rep(alldata.Table$genelist[i],each = 6)
q <- ggplot(celldata.Table.Long,fill = genelist[i])) +
geom_boxplot()+
xlab("Gene variant")+
ylab("Relative proportions")+
theme_bw()
q + stat_compare_means(aes(group = Gene1),label="p.signif")
}
第一个问题是“ $ Gene1”被识别为基因1的列,即使“ genelist [1]”对应于“ Gene1”,也无法识别“ genelist [1]”。 (我收到错误消息“未知或未初始化的列:genelist
”)。我找不到解决此问题并使之正常工作的方法。如果可以使用,我将尝试使脚本为每个图生成一个png。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。