R 因为循环提前结束-为什么?

R 因为循环提前结束-为什么?,r,R,我有一个循环,应该运行大约300000次,但当我将数据绑定到数据帧时,循环结束于55次,我不知道发生了什么 所讨论的循环是: TrendlineMeta <- data.frame("FutureRecord" = character(), "System" = numeric(), "Intercepts" = numeric(), "Slopes" = numeric(), stringsAsFactors = FALSE) for (i in unique(TrendingData

我有一个循环,应该运行大约300000次,但当我将数据绑定到数据帧时,循环结束于55次,我不知道发生了什么

所讨论的循环是:

TrendlineMeta <- data.frame("FutureRecord" = character(), "System" = numeric(), "Intercepts" = numeric(), "Slopes" = numeric(), stringsAsFactors = FALSE)

for (i in unique(TrendingData$FutureRecord)){
  FilteredList <- TrendingData[TrendingData$FutureRecord == i,]

  Regressed <- lm(FilteredList$Value ~ FilteredList$Time)#, na.action = na.omit)

  newrow <- c("FutureRecord"=j, "System"=max(as.character(FilteredList$System)), "Intercepts"=summary(Regressed)$coefficients[1,1], "Slopes"=summary(Regressed)$coefficients[2,1])
  TrendlineMeta <- rbind(TrendlineMeta, data.frame(as.list(newrow), stringsAsFactors = FALSE))
}
55分钟后结束

然而,这个循环:

TrendlineMeta <- data.frame("FutureRecord" = character(), "System" = numeric(), "Intercepts" = numeric(), "Slopes" = numeric(), stringsAsFactors = FALSE)

for (i in unique(TrendingData$FutureRecord)){
  FilteredList <- TrendingData[TrendingData$FutureRecord == i,]

  Regressed <- lm(FilteredList$Value ~ FilteredList$Time)#, na.action = na.omit)

  #newrow <- c("FutureRecord"=j, "System"=max(as.character(FilteredList$System)), "Intercepts"=summary(Regressed)$coefficients[1,1], "Slopes"=summary(Regressed)$coefficients[2,1])
  #TrendlineMeta <- rbind(TrendlineMeta, data.frame(as.list(newrow), stringsAsFactors = FALSE))
}
很好


我做错了什么?我是R新手,所以没有什么东西会冲着我跳。

所以,这只是针对您的问题的一个尝试,但是如果不查看底层数据集,这有点困难。我使用的是Hadley的purrr、tidyr、plyr和dplyr包

它可以在不使用循环的情况下完成您想要做的事情

partA <- TrendingData %>%
  split(.$FutureRecord) %>%
  map(~ lm(Value ~ Time, data = .)) %>%
  map(summary) %>%
  map("coefficients") %>% 
  map(data.frame) %>% 
  map(~ select(.x, Estimate) %>%
        mutate(coef = row.names(.))) %>%
  ldply(rbind) %>%
  rename(FutureRecord = .id) %>%
  spread(coef, Estimate)

这行吗?

不要在循环中增长对象。对于您的任务,您可以很容易地使用其中一个split-apply-combine函数。FutureRecord=j中的j是您代码前面定义的静态对象吗?@Sebastian,应该是FutureRecord=i而不是j。我试过做j
partB <- TrendingData %>%
  select(FutureRecord, System) %>%
  group_by(FutureRecord)  %>%
  filter(System == max(System)) %>%
  ungroup
left_join(partA, partB)