并非所有值都存储在循环中

时间:2017-02-24 16:50:18

标签: r store

我想将值存储在“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

1 个答案:

答案 0 :(得分:0)

不需要循环。 可以是一种更简单的方法,但是两个基于集合的步骤比两个循环更好。这是我尝试做的两种方式:

<强>碱

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])

<强> data.table

{{1}}