R语言 如何基于两列而不是单列将表透视为宽

w8f9ii69  于 2023-05-11  发布在  其他
关注(0)|答案(2)|浏览(156)

我有这样的数据

df <- data.frame(ptid = rep(1:2, each = 6),
                 num = rep(1:3, each = 4),
                 type = rep(c("type1", "type2"), each = 6),
                 time = rep(1:3, times = 4),
                 volume = rnorm(12))

现在,它是长格式,我应该如何根据时间和类型将其更改为宽格式,而不是一个:比如time 1 type 1,time 2 type 1,time 3 type 1,time 1 type 2,time 2 type 2,time 3 type 3,time 3 type 3...?
我写了这段代码

df_wide <- df %>%
  pivot_wider(names_from = c("time", "type"),
              values_from = "volume",
              names_prefix = "time",
              names_sep = "")

但是它说这个量不足以识别,而且不能工作。谢谢帮忙~~!

uqzxnwby

uqzxnwby1#

您有匹配ptid/num/type/time的观测。如果您希望它们是单独的行而不是该位置的列表,请添加一个标识符以区分它们:

df %>%
  dplyr::mutate(iteration = dplyr::row_number(), .by = c(ptid:time)) %>%
  pivot_wider(names_from = c("time", "type"),
              values_from = "volume",
              names_prefix = "time",
              names_sep = "")

# A tibble: 6 × 9
   ptid   num iteration time1type1 time2type1 time3type1 time1type2 time2type2 time3type2
  <int> <int>     <int>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1     1         1     0.0202       1.09      -1.72      NA        NA         NA    
2     1     1         2    -0.473       NA         NA         NA        NA         NA    
3     1     2         1    NA           -1.06      -1.02      NA        NA         NA    
4     2     2         1    NA           NA         NA         -1.11     -0.494     NA    
5     2     3         1    NA           NA         NA         -1.34     -0.146     -1.08 
6     2     3         2    NA           NA         NA         NA        NA         -0.463
dgsult0t

dgsult0t2#

library(dplyr)
library(tidyr)

df %>% 
  unite(time_type, c(time, type), sep = "") %>% 
  pivot_wider(names_from = time_type,
              values_from = volume,
              names_prefix = "time", 
              values_fn = list) %>% 
  unnest(cols = c(time1type1, time2type1, time3type1, time1type2, time2type2, time3type2))
ptid   num time1type1 time2type1 time3type1 time1type2 time2type2 time3type2
  <int> <int>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
1     1     1      0.864     -1.02       0.577     NA         NA         NA    
2     1     1      1.33      -1.02       0.577     NA         NA         NA    
3     1     2     NA         -0.909     -1.30      NA         NA         NA    
4     2     2     NA         NA         NA          0.255     -0.549     NA    
5     2     3     NA         NA         NA         -0.213      0.139     -1.59 
6     2     3     NA         NA         NA         -0.213      0.139     -0.384

相关问题