2017-02-24 97 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每年的最小值以及它的保单号是从哪里来的?但我编辑了我的原始答案。如果这不是你正在寻找的答案,那么你将不得不创建一个示例输出。 –