【问题标题】:How to Create a New Variable Based on a List on Vector如何基于 Vector 上的列表创建新变量
【发布时间】:2023-02-01 02:48:14
【问题描述】:

在 R 中,

a) 包含每个州所属地区(东北、南部、中北部、西部)的列表

regions <- list(
    west = c("WA", "OR", "CA", "NV", "AZ", "ID", "MT", "WY",
                     "CO", "NM", "UT"),
    south = c("TX", "OK", "AR", "LA", "MS", "AL", "TN", "KY",
                        "GA", "FL", "SC", "NC", "VA", "WV"),
    midwest = c("KS", "NE", "SD", "ND", "MN", "MO", "IA", "IL",
                            "IN", "MI", "WI", "OH"),
    northeast = c("ME", "NH", "NY", "MA", "RI", "VT", "PA", 
                                "NJ", "CT", "DE", "MD", "DC")
)

和 b) 带有状态和死亡的数据框

#A tibble:

  state      Deaths 
  <chr>          <int>    
1 AL             29549      
2 AK               741      
3 AR             50127   
4 NJ            15142   
5 CA            175213   
6 IA            1647   
...

我想创建一个新变量,将每个州与其所在地区相匹配并总结死亡人数。执行此操作的最佳方法是什么?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以将 stacklist 添加到一个两列的 data.frame 中并进行连接

    library(dplyr)
    stack(regions)  %>%
       left_join(df1, ., by = c("state" = "values")) %>%
       rename(region = 'ind')
    

    -输出

       state Deaths    region
    1    AL  29549     south
    2    AK    741      <NA>
    3    AR  50127     south
    4    NJ  15142 northeast
    5    CA 175213      west
    6    IA   1647   midwest
    

    如果 df1 有重复的行,我们可以按 summarise 进行分组

    stack(regions)  %>%
       left_join(df1, ., by = c("state" = "values")) %>%
       group_by(state, region = 'ind') %>%
       summarise(Deaths = sum(Deaths, na.rm = TRUE), .groups = 'drop')
    

    数据

    df1 <- structure(list(state = c("AL", "AK", "AR", "NJ", "CA", "IA"), 
        Deaths = c(29549L, 741L, 50127L, 15142L, 175213L, 1647L)), 
    class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多