R语言 构造将tibble整形为一行

kh212irz  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(128)

我有个小问题

df <- dplyr::tibble(id = c(1, 2, 3), n = c(1, 2, 1), max = c(-10, 2, 3), class = c(0, 0, 0), Time = c(1, 1, 1))     
id     n   max class  Time
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1   -10     0     1
2     2     2     2     0     1
3     3     1     3     0     1

classTime是常量,所以我想将id列与nmax列连接起来,这样。

class  Time `1_n` `1_max` `2_n` `2_max` `3_n` `3_max`
  <dbl> <dbl> <dbl>   <dbl> <dbl>   <dbl> <dbl>   <dbl>
1     0     1     1     -10     2       2     1       3

我用pivot_wider试过了,但是不能让它工作。有什么想法吗?

efzxgjgh

efzxgjgh1#

library(tidyr)
pivot_wider(df, names_from = "id", values_from = n:max, 
            names_glue = "{id}_{.value}", names_vary = "slowest")

# A tibble: 1 × 8
  class  Time `1_n` `1_max` `2_n` `2_max` `3_n` `3_max`
  <dbl> <dbl> <dbl>   <dbl> <dbl>   <dbl> <dbl>   <dbl>
1     0     1     1     -10     2       2     1       3

相关问题