Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

r - 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,
)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...