R语言 如何基于向量上的列表创建新变量

ct2axkht  于 2023-02-01  发布在  其他
关注(0)|答案(2)|浏览(198)

在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)具有状态和死亡的 Dataframe

#A tibble:

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

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

s4n0splo

s4n0splo1#

我们可以stacklist到一个两列的数据框架中,然后进行连接

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"))
r6l8ljro

r6l8ljro2#


我在这里所做的只是将列表创建到数据框中,其中一列表示区域,另一列表示州列表

这里我使用了一个dplyr函数“right_join”,它将根据特定的值“排列”不同的行和列,所以这里我们希望根据状态排列相应的区域。

相关问题