如何通过分组和过滤将行扩展到列? [英] How to spread rows to columns by grouping and filtering?
本文介绍了如何通过分组和过滤将行扩展到列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似这样的数据集:
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,
)
但是现在,我想按id"对数据进行分组,然后将行切换到列.我认为这不像转置.
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?
推荐答案
我们可以使用 pivot_wider
它可以采用多个 values
列.
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
这篇关于如何通过分组和过滤将行扩展到列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文