问题
I have a data set something like this:
df_1 <- tribble(
~id, ~type, ~min_price, ~max_price,
"1", "X", 10, 40,
"1", "Y", 20, 50,
"2", "X", 18, 40,
"2", "Y", 34, 50,
"2", NA, 15, 70,
"3", "X", 40, 90,
"3", "Y", 23, 100,
)
But now, I want to group the data by "id", and then switch the rows to columns. I think this is not something like transpose.
df_1 <- tribble(
~id, ~min_price_X, ~min_price_Y, ~min_price_NA, ~max_price_X, ~max_price_Y, ~max_price_NA,
"1", 10, 10, NA, 40, 50, NA,
"2", 18, 34, 15, 40, 50, 70,
"3", 40, 23, NA, 90, 100, NA,
)
Would you have any suggestion to get this data?
回答1:
We can use pivot_wider
which can take multiple values
column.
tidyr::pivot_wider(df_1, names_from = type, values_from = c(min_price, max_price))
# A tibble: 3 x 7
# id min_price_X min_price_Y min_price_NA max_price_X max_price_Y max_price_NA
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1 10 20 NA 40 50 NA
#2 2 18 34 15 40 50 70
#3 3 40 23 NA 90 100 NA
回答2:
You can try this:
library("reshape2")
dcast(melt(df_1, id.vars = c("id", "type")), id ~ variable + type)
The result would be:
id min_price_X min_price_Y min_price_NA max_price_X max_price_Y max_price_NA
1 1 10 20 NA 40 50 NA
2 2 18 34 15 40 50 70
3 3 40 23 NA 90 100 NA
来源:https://stackoverflow.com/questions/59090576/how-to-spread-rows-to-columns-by-grouping-and-filtering