R错误“总和对因素无意义”

问题描述 投票:17回答:1

我有一个名为rRna_RDP_taxonomy_phylum的文件,其中包含以下数据:

364  "Firmicutes"            39.31
244  "Proteobacteria"        26.35
218  "Actinobacteria"        23.54
65   "Bacteroidetes"         7.02
22   "Fusobacteria"          2.38
6    "Thermotogae"           0.65
3     unclassified_Bacteria  0.32
2    "Spirochaetes"          0.22
1    "Tenericutes"           0.11
1     Cyanobacteria          0.11

我正在使用此代码在R中创建饼图:

if(file.exists("rRna_RDP_taxonomy_phylum")){
    family <- read.table ("rRna_RDP_taxonomy_phylum", sep="\t")
    piedat <- rbind(family[1:7, ],
                as.data.frame(t(c(sum(family[8:nrow(family),1]),
                                "Others",
                                sum(family[8:nrow(family),3])))))
    png(file="../graph/RDP_phylum_low.png", width=600, height=550, res=75)
    pie(as.numeric(piedat$V3), labels=piedat$V3, clockwise=TRUE, col=graph_col, main="More representative Phyliums")
    legend("topright", legend=piedat$V2, cex=0.8, fill=graph_col)
    dev.off()
    png(file="../graph/RDP_phylm_high.png", width=1300, height=850, res=75)
    pie(as.numeric(piedat$V3), labels=piedat$V3, clockwise=TRUE, col=graph_col, main="More representative Phyliums")
    legend("topright", legend=piedat$V2, cex=0.8, fill=graph_col)
    dev.off()
}

我一直在使用这个代码用于不同的数据文件,它工作正常,但随着文件显示adobe它崩溃返回以下消息:

Error in Summary.factor(c(6L, 2L, 1L), na.rm = FALSE) : 
  sum not meaningful for factors
Calls: rbind -> as.data.frame -> t -> Summary.factor
Execution halted

我需要理解为什么它会崩溃这个文件,如果有任何方法可以防止这种错误。

谢谢!

r r-factor categorical-data
1个回答
38
投票

当你试图调用sum(x)并且x是一个因素时会出现错误。

这意味着你的一个列,虽然它们看起来像数字实际上是因素(你看到的是文本表示)

简单修复,转换为数字。但是,它需要先转换为角色的中间步骤。使用以下内容:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

有关为什么需要中间as.character步骤的详细解释,请看一下这个问题:How to convert a factor to integer\numeric without loss of information?

© www.soinside.com 2019 - 2024. All rights reserved.