首页 > 解决方案 > 将结果写回 lastrow + 1 到新创建的数据帧

问题描述

我正在尝试将 for 循环中的结果写回我创建的新数据帧。我想遍历每一行,然后将结果写入数据框的最后一行(lastrow + 1)。不幸的是,我被卡住了,无法将结果写回。

#create a new dataframe
results<- data.frame(Fields=character(), Employee=character(), Plan=character())

a<-COMP30$PFRPrint_Has_Plan
b<-COMP30$PFRPrint_Is_Eligible
c<-COMP30$`Employee ID`
d<-results$Employee

matches<-cbind(a,b,c)
res<-cbind(d)
for (k in 1:nrow(matches)){
  if (matches[k,1]==TRUE & matches[k,2]==FALSE){
    results[nrow(results$Employee)+1,1]<-matches[k,3]   
  }
}

标签: r

解决方案


如果我已经正确理解了您要执行的操作,那么您正在尝试过滤COMP30$`Employee ID`到那些情况,其中COMP30$PFRPrint_Has_Plan == TRUECOMP30$PFRPrint_Is_Eligible == FALSE.

那么为什么不干脆去

library(dplyr)
results <- COMP30 %>%
  filter(PFRPrint_Has_Plan,
         !PFRPrint_Is_Eligible) %>%
  select("Employee ID") # Might need backticks for that column name

由于您的循环没有为Fieldsor列指定值,因此我假设您稍后Plan将它们添加到results


推荐阅读