【问题标题】:Creating proportion variables of panel data in R (state/year)在R中创建面板数据的比例变量(州/年)
【发布时间】:2020-09-04 14:13:56
【问题描述】:

我有自 1990 年以来各州人口的种族普查数据。我想在 R 工作室的年度/州一级做两件事:1. 将所有西班牙裔/拉丁裔的任何种族群体汇总为一个全新的种族组,“西班牙裔/拉丁裔” 2. 从总人口中创建每个种族群体的百分比。比如我想知道1990年阿拉巴马州非西班牙裔黑人的比例The image shows what my data looks like

【问题讨论】:

    标签: r aggregate panel data-cleaning summarize


    【解决方案1】:

    我不是 100% 清楚你需要你的最终结果#1 是什么......但如果你最终需要的是“种族”列来表示“西班牙裔或拉丁裔”,你可以这样做:

    Data$Race[(Data$Ethnicity == "Hispanic or Latino")] <- "Hispanic or Latino"
    

    您还可以像这样组合 Ethnicity 和 Race 列中的内容:

    Data$Race[(Data$Ethnicity == "Hispanic or Latino")]<- paste(Data$Race[((Data$Ethnicity == "Hispanic or Latino")],Data$Ethnicity[(Data$Ethnicity == "Hispanic or Latino")])
    

    对于#2...

    #Load library
    library(dplyr)
    #Make test data
    Data <- data.frame(Year = c(1990,1990,1991,1991),
                       State = c("AL", "MO", "AL", "MO"),
                       Population = c(1,2,2,3),
                       Race = c("Black", "Hispanic", "Hispanic", "Black"))
    #Calculate total population
    total_pop <- sum(Data$Population)
    # Group by and calculate statistic, save to new 'df' dataframe
    df <- Data %>%
      group_by(Year, State, Race) %>%
      summarise(percent = sum(Population)/total_pop)
    

    【讨论】:

      猜你喜欢
      • 2015-08-02
      • 2019-01-12
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 2022-12-29
      相关资源
      最近更新 更多