【问题标题】:Not all values storing in a loop并非所有值都存储在循环中
【发布时间】:2017-07-15 14:32:50
【问题描述】:

我想将值存储在“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”矩阵的图像。

【问题讨论】:

  • 您需要提前创建yy 并确定yy 中每个值的存储位置,即yy[ij,ik]。
  • 你能给我们一些你正在使用的变量的样本数据吗?可能有矢量化或使用lapply 的方法,具体取决于您要执行的操作。
  • 我同意,但是对于每个 ij 都有多个行/值,如输出中所示的“min”估计并应该存储。
  • @Oliver。请查看我的问题中的图片。
  • 我们不能对图像做任何事情。看到这个:stackoverflow.com/questions/5963269/…

标签: r store


【解决方案1】:

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

基础

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

【讨论】:

  • 如果要删除重复行,请使用unique()
  • 感谢您的及时回复。但是,这不是我想要的答案。我想知道每年每个保单号码的“min_dist”。希望对您有所帮助。
  • 当我问“所以你期望 min_dist 每年的最小值和它来自的保单号?”时,你不是这么说的。但我已经编辑了我原来的答案。如果这不是您要寻找的答案,那么您将不得不创建一个示例输出。
  • 非常感谢。这是我一直在寻找的答案。非常感谢。
  • 没问题。如果您对它感到满意,请将其标记为正确。
猜你喜欢
  • 2015-11-26
  • 2019-05-16
  • 2017-06-04
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 2023-03-22
  • 2014-06-08
  • 2016-02-02
相关资源
最近更新 更多