【问题标题】:R: Populating matrix from loopR:从循环填充矩阵
【发布时间】:2014-11-29 17:40:28
【问题描述】:

我有一个与此非常相似的问题:Populating a data frame in R in a loop。我似乎无法循环填充我的矩阵。

myDF <- read.csv('corpusFiltered.txt.gz', header = TRUE, sep = '\t')
phylum = sort(unique(myDF$PHYLUM))
myDF.mean = ddply(myDF, .(ENVIRONMENT, FILENAME, PHYLUM), summarize, MeanX = mean(X, na.rm=TRUE) ) 

df_all = myDF.mean[c(4, 3)] #select only the X and Phylum
c_all = unstack(df_all) #restructure dataframe

columnPhylum1 = matrix(ncol=1, nrow=length(phylum))

GET_X = function(dataset)
{
   for (i in 1:length(phylum))
   {   
      print(phylum[i]) 
      columnPhylum1[i,] <- phylum[i] #this does not populate the matrix. still 'NA'
   }   
}
GET_X(c_all)
print('')
print(columnPhylum1)

这不起作用。输出是:

[1] Actinobacteria
Levels: Actinobacteria Bacteroidetes Chlamydiae Crenarchaeota Deinococcus-Thermus Euryarchaeota Firmicutes Proteobacteria Spirochaetes Tenericutes ***
[1] Bacteroidetes
[1] Chlamydiae
[1] Crenarchaeota
[1] Deinococcus-Thermus
[1] Euryarchaeota
[1] Firmicutes
[1] Proteobacteria
[1] Spirochaetes
[1] Tenericutes
[1] ""
      [,1]
 [1,]   NA  
 [2,]   NA  
 [3,]   NA  
 [4,]   NA  
 [5,]   NA  
 [6,]   NA  
 [7,]   NA  
 [8,]   NA  
 [9,]   NA  
[10,]   NA 

***为简洁起见,我从除第一个原核生物(放线菌)之外的所有生物中删除了子序列“级别”信息。

但是,如果我制作一个人造矩阵...

sig= matrix(ncol=1, nrow=length(phylum))
for (i in 1:length(phylum)){sig[i,]<-i}
print(sig)

这就像一个魅力。

     [,1]
 [1,]    1   
 [2,]    2   
 [3,]    3   
 [4,]    4   
 [5,]    5   
 [6,]    6   
 [7,]    7   
 [8,]    8   
 [9,]    9   
[10,]   10  

也许我只见树不见林;我已经检查了明显的东西(例如正确的变量名),但我找不到任何问题。我能看到的唯一区别是顶部从函数调用循环。我不明白为什么我会从“相同”代码中得到不同的行为。非常感谢任何帮助。

【问题讨论】:

    标签: r loops matrix


    【解决方案1】:

    我猜问题是您试图在数字矩阵中复制因子变量的值(这就是为什么您的“人造”矩阵确实有效,因为它插入的是数字,而不是因子)。我真的不明白为什么你需要它在矩阵中,因为你试图复制你已经拥有的整个向量。无论如何,也许这个简单的代码才是你真正想要做的:

    vect <- factor(c('foo', 'bar', 'foo'), levels = c('foo', 'bar'))
    mat <- as.matrix(vect)
    mat
    

    哪个输出:

        [,1] 
    [1,] "foo"
    [2,] "bar"
    [3,] "foo"
    

    编辑:在您的具体情况下,这将转化为:

    columnPhylum1 <- as.matrix(phylum)
    

    【讨论】:

    • 您对代码是正确的;我想做其他事情,这是验证过程的一种方式。你对为什么人造矩阵有效是正确的。让我用我真正想要捕获的变量来尝试我的函数。如果可行,我会接受你的回答。
    • Francisco --> 你的回答并没有完全解决我的问题,但你让我更接近问题的根源,更接近提出更好的问题(希望将来能找到解决方案)。出于这个原因,我将接受你的回答。谢谢。
    【解决方案2】:

    这可能与您的phyla 向量包含因子有关。

    尝试将phyla 强制转换为字符向量:

    char_phyla <- as.character(phyla)
    

    如果可行,您可以在不自动分解的情况下读取 csv 数据:

    myDF <- read.csv('corpusFiltered.txt.gz', header=T, sep='\t', stringsAsFactors=F)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2013-01-19
      • 1970-01-01
      • 2011-09-29
      相关资源
      最近更新 更多