如何将值映射到数据框R中的值列表

当前,我有一个根据状态进行细分的数据框,例如:

  STATE     
1 Connecticut
2 Maine
3 New York
4 Pennsylvania

我希望能够根据区域对这些状态进行细分,并希望基于该列:

  STATE        REGION
1 Connecticut  New England
2 Maine        New England
3 New York     Mid-Atlantic
4 Pennsylvania Mid-Atlantic

目前,我有这个:

ne <- c("Connecticut", "Maine", "Massachusetts", "New Hampshire", "Rhode Island", "Vermont")
values <- c("New England")
df$REGION <- values[match(jails_cleaned$STATE, ne)]

midatlantic <- c("New Jersey", "New York", "Pennsylvania")
values2 <- c("Mid-Atlantic")
df$REGION <- values[match(df$STATE, midatlantic)]

但是在运行时,它仅匹配新英格兰的值,而不匹配中大西洋。

评论
  • aumujun
    aumujun 回复

    Create a dataframe that you will merge to your jails_cleaned data

    df_stats <- data.frame(
      'STATE' = c(
        c("Connecticut", "Maine", "Massachusetts", "New Hampshire", "Rhode Island", "Vermont"),
        c("New Jersey", "New York", "Pennsylvania")),
      'REGION' = c(rep("New England",6), rep("Mid-Atlantic",3))
    )
    
    df_stats
              STATE       REGION
    1   Connecticut  New England
    2         Maine  New England
    3 Massachusetts  New England
    4 New Hampshire  New England
    5  Rhode Island  New England
    6       Vermont  New England
    7    New Jersey Mid-Atlantic
    8      New York Mid-Atlantic
    9  Pennsylvania Mid-Atlantic
    
    merge(jails_cleaned,df_stats, by = 'STATE')