【问题标题】:Write results back to lastrow + 1 to a newly create dataframe将结果写回 lastrow + 1 到新创建的数据框
【发布时间】:2020-02-20 21:38:48
【问题描述】:

我正在尝试将 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]   
  }
}

【问题讨论】:

  • 请提供可重现且最少的样本数据以及您的预期输出。
  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • @conor - 我想为多个场景执行循环并返回结果,所以我不确定过滤器方法是否有效,或者我不知道如何修改它以复合我的结果一次我添加了额外的 if 场景

标签: r


【解决方案1】:

如果我正确理解了您要执行的操作,则您正在尝试将 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

由于您的循环没有指定 FieldsPlan 列的值,我假设您稍后会将它们添加到 results

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2023-03-17
    • 2018-07-31
    • 2016-11-19
    • 2023-01-27
    • 2018-03-17
    • 1970-01-01
    • 2020-12-22
    • 2018-08-02
    相关资源
    最近更新 更多