R 数据行、变量和值在计算过程中重新排序

R 数据行、变量和值在计算过程中重新排序,r,R,在绘图之前将数据添加到矩阵时,我遇到R问题: > resFile <- read.csv("file.csv") > print(resFile) Gene Virus Expression Percentage 1 ga 1Virus 2.738598e-02 38.590745 2 ga 2Virus 3.247252e-02 64.331929 3 ga PIC 4.235604e-02 114.348940 4

在绘图之前将数据添加到矩阵时,我遇到R问题:

> resFile <- read.csv("file.csv")
> print(resFile)
     Gene Virus  Expression    Percentage
1    ga   1Virus 2.738598e-02  38.590745
2    ga   2Virus 3.247252e-02  64.331929
3    ga   PIC    4.235604e-02  114.348940
4    ga   MOCK   1.976032e-02  0.000000        
> samples <- unique(resFile$Virus)
> genes <- unique(resFile$Gene)
> numGene <- length(genes)
> numSmpl <- length(samples)

> mat <- matrix(ncol=numGene,nrow=numSmpl,dimnames=list(samples,genes))
> mat[samples,genes]<-resFile$Percentage
> print(mat)
              ga 
1Virus  38.59074
2Virus  64.33193
PIC      0.00000
MOCK   114.34894
如您所见,百分比值在我的PIC和模拟样本之间切换。整个列也会发生这种情况,看起来值是按字母顺序而不是按符号顺序添加的


为什么会发生这种情况?我该如何避免这种情况?

您的线路有几个问题:

mat[samples,genes] <- resFile$Percentage

关键的区别在于,我已经将因子变量转换为字符,并使用矩阵而不是两个向量编制索引-参见?“['对于数组索引的更好解释,我无法理解。

你只会得到这种奇怪,因为你在CSV中读取时使用了恼人的默认stringsAsFactors=TRUE。因此,你所有的字符串列都变成了factor,而且它们使用了默认的factor…,ordered=F。你可以将它们作为字符串读取,然后转换为factor。。如果您喜欢,则为

然后,每当您看到有人从uniquedf$factorCol而不是标签构造矩阵/向量时,您都会重新讨论排序问题,除非该因子已排序

在您的情况下,您甚至不需要创建矩阵,您可以直接从数据帧切片resFile[,c'Virus','Percentage']获取x,y系列

现在,如果您希望为每个基因获得一个组,那么只选择病毒,百分比列,使用dplyr:

> require(dplyr)
> ga_slice <- resFile %>% group_by(Gene) %>% select(Virus,Percentage) %>% ungroup() %>% select(-Gene)
Source: local data frame [4 x 2]

   Virus Percentage
1 1Virus   38.59074
2 2Virus   64.33193
3    PIC  114.34894
4   MOCK    0.00000

什么是样本和基因?它们只是用来为矩阵生成标题的载体。样本是如何排序的?样本是根据@Miff的答案排序的!我更新了我的问题。谢谢你的帮助。我只想指出显而易见的是,1Virus、2Virus、PIC、MOCK是按字母顺序排列的,而你得到它们的原因是irritating default read.csv default.STRINGSASFORTS=T。请看我的回答谢谢!是as.character做的。不过,不需要cbind。我不知道STRINGSASFORTS参数TRUE default,添加STRINGSASFORTS=FALSE也解决了我的问题。哦,在我的例子中,我实际上需要创建一个矩阵,因为问题只是一个small是我全部代码的一部分,不过还是要谢谢你。
resFile <- read.csv("res.csv", stringsAsFactors=F)

resFile[, c('Virus','Percentage')]
   Virus Percentage
1 1Virus   38.59074
2 2Virus   64.33193
3    PIC  114.34894
4   MOCK    0.00000

> as.matrix(resFile[, c('Virus','Percentage')])
     Virus    Percentage 
[1,] "1Virus" " 38.59074"
[2,] "2Virus" " 64.33193"
[3,] "PIC"    "114.34894"
[4,] "MOCK"   "  0.00000"
# Creating a matrix from slices of dataframe isn't desirable, not just for the row-ordering, but also because all entries are coerced to string. So just don't do it.
> require(dplyr)
> ga_slice <- resFile %>% group_by(Gene) %>% select(Virus,Percentage) %>% ungroup() %>% select(-Gene)
Source: local data frame [4 x 2]

   Virus Percentage
1 1Virus   38.59074
2 2Virus   64.33193
3    PIC  114.34894
4   MOCK    0.00000