Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...