【问题标题】:for loop to populate dataframefor循环填充数据框
【发布时间】:2018-02-26 20:50:29
【问题描述】:

我正在尝试使用 for 循环的结果填充数据框,但我遗漏了一些东西。我已经查看了过去有关此的问题,但我无法理解解决方案,所以...

虚构数据:

df <- data.frame(RA = c(rep("14005", 3), rep("14158", 3), rep("15458", 2), rep("15302", 2)),
             Level = c(rep("Grad", 6), rep("Undergrad", 4)),
             EntryYear = c(rep(2014, 6), rep(2015, 4)),
             ExitYear = c(rep(2016, 3), rep(2017, 3), rep(2018, 4)))

我想用特定 dplyr 管道的结果填充数据框:

df %>% 
filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>% 
distinct(RA) %>% 
summarise(year = n())

year 是我感兴趣的特定年份(在我的原始数据中,它是从 2010 年到 2017 年)。上面的公式是粗略计算给定年份有多少学生注册的。 [我将使用另外两个公式来计算毕业生和新生的数量,因此我将有两个更多的行/列]。并且:

start.year <- 2010
end.year <- 2017

所以,我做了这个for循环,看看它是否有效:

for (year in start.year:end.year){
  mat <- df %>% 
    filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>% 
    distinct(RA) %>% 
    summarise(year= n())
  print(mat)
}

它确实打印了我想要的内容,但是我无法将其写入数据帧...预期结果是一个包含 7 行的数据帧。 最终结果是一个包含 7 行和 3 列的数据框(我将应用的另外两个公式/管道)。

【问题讨论】:

    标签: r for-loop dplyr


    【解决方案1】:

    由于您已经在使用dplyr,因此也很容易使用purrr 为您合并data.frames

    library(purrr)
    map_df(start.year:end.year, function(year) {
      mat <- df %>% 
        filter(Level == "Grad" & EntryYear <= year & ExitYear >= year) %>% 
        distinct(RA) %>% 
        summarise(year= n())
    })
    

    【讨论】:

    • 这很漂亮,谢谢!我以前从未使用过 purrr - 我想我会熟悉它。
    • 让我抓住机会:我正在尝试向我新创建的数据框添加另一列,但它只返回我创建的最后一个变量......我如何在这个函数中完成这一切?
    【解决方案2】:

    只需在最终代码中添加这两行:

    new_df <- data.frame(). # <- this one
    for (year in start.year:end.year){
        mat <- df %>% 
            filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>% 
            distinct(RA) %>% 
            summarise(year= n())
        new_df <- rbind(new_df, mat) # <- this one
    }
    

    【讨论】:

      【解决方案3】:
      for (year in start.year:end.year){
        mat <- df %>% 
          filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>% 
          distinct(RA) %>% 
          summarise(year= n())
        print(mat)
      
        if (year<2011){
      
          final <- as.data.frame(mat)
      
        }
      
        else{
      
          final <- rbind(final,as.data.frame(mat))
      
        }
      }
      

      【讨论】:

        【解决方案4】:
        # load packages
        library(plyr)
        library(dplyr)
        
        # Filter function
        filterdf<-function(year, level){
          mat <- df %>% 
            filter(Level == level, EntryYear <= year, ExitYear >= year) %>% 
            distinct(RA) %>% 
            summarise(year= n())
          colnames(mat)<-paste0(level, "_number")
          return(mat)
        }
        
        # Create your input conditions
        input<-as.data.frame(seq(2010,2017))
        colnames(input)<-"year"
        input$level<-"Grad"
        
        # Output to a dataframe
        output<-mdply(input,filterdf)
        

        【讨论】:

          【解决方案5】:

          这是tidyverse 替代方案:

          library(tidyverse)
          df %>%
            filter(Level=="Grad") %>%
            mutate(year = map2(EntryYear,ExitYear,~.x:.y)) %>%
            unnest(year) %>%
            distinct(RA,year) %>%
            count(year)
          
          # # A tibble: 4 x 2
          #    year     n
          #   <int> <int>
          # 1  2014     2
          # 2  2015     2
          # 3  2016     2
          # 4  2017     1
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-11-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多