2014-05-01 96 views
-1

在R中,我使用for循環遍歷大數據框,嘗試將第*列第7列中的整數放入另一個矩陣中的特定索引。特定索引對應於大數據框中的索引(再次在第* i *行中,而是第2和第4列)。例如,假設我的數據幀有data_frame [1,2] = 5,data_frame [1,4] = 12,data_frame [1,7] = 375。我想把375放入索引中的行,其中行的名稱爲5,列的名稱爲12.R中的數據框到矩陣

但是,問題(我認爲)是當我做col_index = which(colnames(matrix) == data_frame [1,2]),它返回整數0.列名在技術上是5,但我注意到它只適用於我做col_index = which(colnames(matrix)==「5」)。我怎樣才能確保(在我的for循環)data_frame [我,2]對應於「5」?

數據被保存爲「走出去」我的矩陣,我想將數據放在被稱爲「M」

m=matrix(nrow=87,ncol=87) 
fips=sprintf("%03d",seq(1,173,by=2)) 
colnames(m)=fips 
rownames(m)=fips 
m[1:40,1:40] 

接下來,第三列是等於27

for(i in 8:2446) 
{ 
if(out[i,3]==27) 
{ 
out_col=out[i,4] 
out_row=out[i,2] 
moves=out[i,7] 
col_index=which(colnames(m)==paste(out_col)) 
row_index=which(rownames(m)==paste(out_row)) 
m[row_index,col_index]=moves 
} 
} 
條件

對不起格式。它將數字放在矩陣中,但它們不是正確的數字,我無法弄清楚什麼是錯的。任何幫助將非常感激!

回答

1

您的示例中存在很多複雜性,但歸結爲替換mat中的值,其中行名,列名和新值存儲在out中。 (!那將是有益的,如果你發佈一個)讓我們從一個重複的例子,開始

# Matrix to have values replaced 
mat <- matrix(0, nrow=3, ncol=3) 
rownames(mat) <- c("1", "2", "3") 
colnames(mat) <- c("4", "5", "6") 
mat 
# 4 5 6 
# 1 0 0 0 
# 2 0 0 0 
# 3 0 0 0 

out <- data.frame(row=c(1, 3, 3), col=c(6, 5, 4), val=c(1, 4, -1)) 
out 
# row col val 
# 1 1 6 1 
# 2 3 5 4 
# 3 3 4 -1 

現在,做更換一個班輪:

mat[cbind(as.character(out$row), as.character(out$col))] <- out$val 
mat 
# 4 5 6 
# 1 0 0 1 
# 2 0 0 0 
# 3 -1 4 0 

基本上,我們索引mat由2列矩陣表示,其中索引矩陣的每一行都是行名和列名。

在你的榜樣,你似乎排除了前7行out,以及任何基於行的上的東西,如realout <- out[out[,3] == 27 & seq(nrow(out)) %in% 8:2446,]這些要求,其中out[,3]不等於27.你可以簡單地亞羣out,然後做替換與realout

請注意,以這種方式進行替換的另一個好處是,它將比在out行中使用for循環快得多。