尝试创建一个列表,我可以循环选择特定数据

Trying to create a list that I can loop through selecting specifc data

提问人:SWeatherby 提问时间:10/10/2023 更新时间:10/11/2023 访问量:29

问:

我不确定为什么当我尝试从以下代码中调用数据时,我得到 NULL 值。我也没有收到错误消息,所以我不太确定从哪里开始解决这个问题。

我希望能够将其放入数据框/表中,但是在这一点上,我希望能够获得 2019 年的总死亡人数和/或获得特定年份每个州的死亡总数。

企图:

years <- c(2018, 2019, 2020, 2021)

yearly_totals <- list()
state_totals <- list()
mcod_totals <- list()
age_range_totals <- list()


for (year in years) {
    
    yr_data <- mcod_df[mcod_df$year == year, ]
    
    # lists for storage
      yearly_totals[[as.character(year)]] <- sum(yr_data$deaths)

  state_totals[[as.character(year)]] <- yr_data %>%
        group_by(state = state) %>%
        summarise(total_deaths = sum(deaths))
  mcod_totals[[as.character(year)]] <- yr_data %>%
        group_by(mcod = multiple_cause_of_death) %>%
        summarise(tot_mcod = sum(deaths))
    
  age_range_totals[[as.character(year)]] <- yr_data %>%
        group_by(state, age_range = five_year_age_groups) %>%
        summarise(age_range_tot = sum(deaths))
    
  }

致电:

yearly_totals[["2020"]]
state_totals[["2020"]]
cat("State Totals for 2020:\n")
print(state_totals[["2020"]], row.names = FALSE)

结果:

> yearly_totals[["2020"]]
NULL
> state_totals[["2020"]]
NULL
> print(state_totals[["2020"]], row.names = FALSE)
NULL
r 列表 for循环

评论

0赞 Chris 10/10/2023
我认为你需要仔细看看你的使用,而不是说,,只是一个猜测。yr_datayr_data[year]

答:

0赞 SWeatherby 10/11/2023 #1

事实证明,我没有考虑数据中的 NULL/NA 值。更新/更正了以下代码:

 years <- c(2018, 2019, 2020, 2021)
    
    yearly_totals <- list()
    state_totals <- list()
    mcod_totals <- list()
    age_range_totals <- list()
    
    for (year in years) {
        yr_data <- mcod_df[mcod_df$year == year, ]


##### skip year if no data
    if (nrow(yr_data) == 0) {
      cat("No data for year", year, "\n")
      next 
    }
##### Lists to store results w/ consideration for NA/NULL values
      yearly_totals[[as.character(year)]] <- sum(yr_data$deaths)

      state_totals[[as.character(year)]] <- yr_data %>%
        filter(!is.na(state)) %>%
        group_by(state = state) %>%
        summarise(total_deaths = sum(deaths, na.rm = TRUE))

      mcod_totals[[as.character(year)]] <- yr_data %>%
      filter(!is.na(multiple_cause_of_death)) %>%
      group_by(mcod = multiple_cause_of_death) %>%
      summarise(tot_mcod = sum(deaths, na.rm = TRUE))


      age_range_totals[[as.character(year)]] <- yr_data %>%
      filter(!is.na(state) & !is.na(five_year_age_groups)) %>%
      group_by(state, age_range = five_year_age_groups) %>%
      summarise(age_range_tot = sum(deaths, na.rm = TRUE))
    }