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