对如何将这个数据框从长到宽重塑感到困惑
Stumped on how to reshape this dataframe from long to wide
我需要将数据框从长改成宽。我想重塑几个变量,但也想保持数据框其余部分的格式。我有一个数据框,其中包含几年的种族、五分位数和收入。
df <- structure(list(year = c(2019, 2019, 2019, 2018, 2018, 2018), race = c("Black Alone","Black Alone", "Black Alone", "Black Alone", "Black Alone", "Black Alone"), quintile = c("Lowest", "Middle", "Highest", "Lowest", "Middle", "Highest"), income = c(8680, 45356, 177659, 7657, 42202, 155520)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
数据帧df
如下所示:
year race quintile income
2019 Black Alone Lowest 8680
2019 Black Alone Middle 45356
2019 Black Alone Highest 177659
2018 Black Alone Lowest 7657
2018 Black Alone Middle 42202
2018 Black Alone Highest 155520
我希望数据框看起来像:
year race Lowest_income Middle_income Highest_income
2019 Black Alone 8680 45356 177659
2018 Black Alone 7657 42202 155520
我不知道从哪里开始来完成这个。如有任何帮助,我们将不胜感激!
我们可以使用
library(dplyr)
library(tidyr)
library(stringr)
df %>%
mutate(quintile = str_c(quintile, '_income')) %>%
pivot_wider(names_from = 'quintile', values_from = income)
-输出
# A tibble: 2 x 5
# year race Lowest_income Middle_income Highest_income
# <dbl> <chr> <dbl> <dbl> <dbl>
#1 2019 Black Alone 8680 45356 177659
#2 2018 Black Alone 7657 42202 155520
我需要将数据框从长改成宽。我想重塑几个变量,但也想保持数据框其余部分的格式。我有一个数据框,其中包含几年的种族、五分位数和收入。
df <- structure(list(year = c(2019, 2019, 2019, 2018, 2018, 2018), race = c("Black Alone","Black Alone", "Black Alone", "Black Alone", "Black Alone", "Black Alone"), quintile = c("Lowest", "Middle", "Highest", "Lowest", "Middle", "Highest"), income = c(8680, 45356, 177659, 7657, 42202, 155520)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
数据帧df
如下所示:
year race quintile income
2019 Black Alone Lowest 8680
2019 Black Alone Middle 45356
2019 Black Alone Highest 177659
2018 Black Alone Lowest 7657
2018 Black Alone Middle 42202
2018 Black Alone Highest 155520
我希望数据框看起来像:
year race Lowest_income Middle_income Highest_income
2019 Black Alone 8680 45356 177659
2018 Black Alone 7657 42202 155520
我不知道从哪里开始来完成这个。如有任何帮助,我们将不胜感激!
我们可以使用
library(dplyr)
library(tidyr)
library(stringr)
df %>%
mutate(quintile = str_c(quintile, '_income')) %>%
pivot_wider(names_from = 'quintile', values_from = income)
-输出
# A tibble: 2 x 5
# year race Lowest_income Middle_income Highest_income
# <dbl> <chr> <dbl> <dbl> <dbl>
#1 2019 Black Alone 8680 45356 177659
#2 2018 Black Alone 7657 42202 155520