2017-02-24 101 views
-2

我想存儲「yy」的值,但我的代碼下面只存儲一行(最後一個值)。請看下面的輸出。有人可以幫助存儲所有的值在「YY」不是所有的值存儲在循環中

在此先感謝。我是一個初學者到R.

arrPol <- as.matrix(unique(TN_97_Lau_Cot[,6])) 
arrYear <- as.matrix(unique(TN_97_Lau_Cot[,1])) 

for (ij in length(arrPol)){ 
    for (ik in length(arrYear)) { 
    newPolicy <- subset(TN_97_Lau_Cot, POLICY == as.character(arrPol[ij]) & as.numeric(arrYear[ik])) 
    yy <- newPolicy[which.min(newPolicy$min_dist),] 
    } 
} 

輸出:

YEAR DIVISION STATE COUNTY CROP POLICY STATE_ABB LRPP min_dist 
1: 2016  8 41  97 21 699609  TN 0  2.6 

這裏是 「TN_97_Lau_Cot」 矩陣的圖像。

enter image description here

+0

你需要提前創建'yy'並查明在'yy'中應該存儲每個值,即'yy [ij,ik]'。 –

+0

你能給我們提供一些你正在使用的變量的樣本數據嗎?根據你想要做什麼,可能會有矢量化或使用'lapply'的方法。 –

+0

我同意,但是對於每個ij,都有多個行/值,如「min」所估計並應存儲的outoput所示。 – user3408139

回答

0

無需循環。有可能是一個更簡單的方法來做到這一點,但兩個基於集合的步驟比兩個循環更好。這是兩種方法,我會嘗試做:

基地

# Perform an aggregate and merge it to your data.frame. 
TN_97_Lau_Cot_Agg <- merge(
    x = TN_97_Lau_Cot, 
    y = aggregate(min_dist ~ YEAR + POLICY, data = TN_97_Lau_Cot, min), 
    by = c("YEAR","POLICY"), 
    all.x = TRUE 
) 

# Subset the values that you want. 
TN_97_Lau_Cot_Final <- unique(subset(TN_97_Lau_Cot_Agg, min_dist.x == min_dist.y)) 

data.table

library(data.table) 

# Convert your data.frame to a data.table. 
TN_97_Lau_Cot <- data.table(TN_97_Lau_Cot) 

# Perform a "window" function that calculates the min value for each year without reducing the rows. 
TN_97_Lau_Cot[, minDistAggregate:=min(min_dist), by = c("YEAR","POLICY")] 

# Find the policy numbers that match the minimum distance for that year. 
TN_97_Lau_Cot_Final <- unique(TN_97_Lau_Cot[min_dist==minDistAggregate, -10, with=FALSE]) 
+0

如果您想刪除重複行,請使用'unique()' –

+0

感謝您的及時回覆。但是,那不是我正在尋找的答案。我想知道每年每個保單編號的「min_dist」。希望能幫助到你。 – user3408139

+0

當我問到「你是否期待min_dist每年的最小值以及它的保單號是從哪裏來的?但我編輯了我的原始答案。如果這不是你正在尋找的答案,那麼你將不得不創建一個示例輸出。 –